<?php
session_start();
$start = microtime();

if ( !$_SESSION['manager'] )
{
    $_SESSION['return'] = $_SERVER['REQUEST_URI'];

    header('Location: index.php');
    exit();
}
else
{
// Читаем системные переменные касаемые загрузки файлов:
    $f_limit = array
    (
	'file_uploads'		=> ini_get('file_uploads'),
	'upload_max_filesize'	=> ini_get('upload_max_filesize'),
	'max_file_uploads'	=> ini_get('max_file_uploads'),
	'post_max_size'		=> ini_get('post_max_size')
    );

// Подгружаем системные конфиги
    require_once('inc/config.db.php');
    require_once('inc/config.smarty.php');
    require_once('core/core.php');
/*
    Привязываем справочники в шаблонизатор
*/

    if ( preg_match('/^opera/i',$_SERVER['HTTP_USER_AGENT']) ) { $smarty->assign('is_opera',TRUE); }
// Менеджеры
    $result = mysql_query('SELECT `id`,`manager_name` FROM `manager` WHERE is_deleted=0 ORDER BY `manager_name`');
    while ( $row = mysql_fetch_assoc($result) )
    {
		$manager[] = $row;
    }
    $smarty->assign('managers',$manager);

// Группы
    $result = mysql_query('SELECT `id`,`group_name` FROM `group` ORDER BY `group_name`');
    while ( $row = mysql_fetch_assoc($result) )
    {
	$group[] = $row;
    }
    $smarty->assign('groups',$group);

// Статусы
    $result = mysql_query('SELECT `id`,`status_name` FROM `status` ORDER BY `status_name`');
    while ( $row = mysql_fetch_assoc($result) )
    {
	$status[] = $row;
    }
    $smarty->assign('statuses',$status);

// Исполнители
    $result = mysql_query('SELECT * FROM `executive` ORDER BY `executive_name`');
    while( $row = mysql_fetch_assoc($result) )
    {
	$executive[] = $row;
    }
    $smarty->assign('executives',$executive);

// Услуги
    $result = mysql_query('SELECT * FROM `service_name` ORDER BY `service_name`');
    while( $row = mysql_fetch_assoc($result) )
    {
	$service_name[] = $row;
    }
    $smarty->assign('service_names',$service_name);

// Тарифы на телефонию
    $result = mysql_query('SELECT * FROM `phone_rate` ORDER BY `rate_name`');
    while( $row = mysql_fetch_assoc($result) )
    {
	$phone_rate[] = $row;
    }
    $smarty->assign('phone_rates',$phone_rate);

// аплинки местной связи
    $result = mysql_query('SELECT * FROM `city_uplink`');
    while( $row = mysql_fetch_assoc($result) )
    {
	$city_uplink[] = $row;
    }
    $smarty->assign('city_uplinks',$city_uplink);

// аплинки зоновой мобильной связи
    $result = mysql_query('SELECT * FROM `zona_mobile_uplink`');
    while( $row = mysql_fetch_assoc($result) )
    {
	$zona_mobile_uplink[] = $row;
    }
    $smarty->assign('zona_mobile_uplinks',$zona_mobile_uplink);
    $smarty->assign('zona_mobile_uplinks_reserve',$zona_mobile_uplink);

// аплинки зоновой стационарной связи
    $result = mysql_query('SELECT * FROM `zona_stationary_uplink`');
    while( $row = mysql_fetch_assoc($result) )
    {
	$zona_stationary_uplink[] = $row;
    }
    $smarty->assign('zona_stationary_uplinks',$zona_stationary_uplink);
    $smarty->assign('zona_stationary_uplinks_reserve',$zona_stationary_uplink);

// аплинки междугородней связи
    $result = mysql_query('SELECT * FROM `long_distance_uplink`');
    while( $row = mysql_fetch_assoc($result) )
    {
	$long_distance_uplink[] = $row;
    }
    $smarty->assign('long_distance_uplinks',$long_distance_uplink);
    $smarty->assign('long_distance_uplinks_reserve',$long_distance_uplink);

// аплинки международной связи
    $result = mysql_query('SELECT * FROM `international_uplink`');
    while( $row = mysql_fetch_assoc($result) )
    {
	$international_uplink[] = $row;
    }
    $smarty->assign('international_uplinks',$international_uplink);
    $smarty->assign('international_uplinks_reserve',$international_uplink);

// все незанятые номера
    $result = mysql_query('SELECT `phone_number` FROM `service_phone_number` where `service_id` is NUlL');
    while( $row = mysql_fetch_assoc($result) )
    {
	$service_phone_number[] = $row;
    }
    $smarty->assign('service_phone_numbers',$service_phone_number);

// Настраиваемые поля: ОСНОВНЫЕ
    $fields = array
    (
	array
	(
	    'title'	=> 'Номер лиц.счёта',
	    'name'	=> 'account_id',
	),
	array
	(
	    'title'	=> 'Название',
	    'name'	=> 'customer_name',
	),
	array
	(
	    'title'	=> 'Номер договора',
	    'name'	=> 'contract_number',
	),
	array
	(
	    'title'	=> 'Контактная информация',
	    'name'	=> 'contact',
	),
	array
	(
	    'title'	=> 'E-Mail',
	    'name'	=> 'email',
	),
	array
	(
	    'title'	=> 'Группа',
	    'name'	=> 'group_name',
	),
	array
	(
	    'title'	=> 'Статус',
	    'name'	=> 'status_name',
	),
	array
	(
	    'title'	=> 'Ответственный менеджер',
	    'name'	=> 'manager_name',
	),
    );

// Настраиваемые поля: ДОПОЛНИТЕЛЬНЫЕ
    $result = mysql_query('SELECT * FROM `field_name` ORDER BY `field_name`');
    while ( $row = mysql_fetch_assoc($result) )
    {
	$arb_fields[] = $row;
	$fields[] = array
	(
	    'title'	=> $row['field_name'],
	    'name'	=> sprintf('custom_field_%d',$row['id']),
	    'id'	=> $row['id'],
	);
    }

    $smarty->assign('customer_fields',$fields);
    $smarty->assign('fields',$arb_fields);

//    die(var_dump($arb_fields));

    switch ( $_GET['action'] )
    {
/*
########################
    ВЫХОД ИЗ СИСТЕМЫ
########################
*/
	case	'logout':
	    if ( mysql_query(sprintf('INSERT INTO `arrival_time` (`manager_id`,`type`,`date_time`,`ip`) VALUES (%d,\'logout\',NOW(),\'%s\')',$_SESSION['manager']['id'],$_SERVER['REMOTE_ADDR'])) )
	    {
		session_destroy();
		header('Location: admin.php');
		exit();
	    }
	    else
	    {
		die(mysql_error());
	    }
	    break;

/*
########################
    СПИСОК КЛИЕНТОВ
########################
*/
	case	'customer.list':
	default:
	    $customer = new webCustomer;
	    $customer->limit(50);	// Кол-во записей на одну страницу

	    if ( !$_SESSION['manager']['is_admin'] )
	    {
#		$customer->addFilter(array('manager_id'=>$_SESSION['manager']['id']));
		$customer->_task->addFilter(array('rm_id'=>$_SESSION['manager']['id']));
	    }

	    if ( $_SESSION['manager']['is_admin'] )
	    {
		if ( $count = mysql_fetch_row(mysql_query('SELECT COUNT(*) FROM `raw_data`')) )
		{
		    $customer->_smarty->assign('raw_data_count',$count[0]);
		}
	    }

	    if ( $_SESSION['filter']['tasks']['only_my'] == 1 )
		$customer->_task->addFilter(array('rm_id'=>$_SESSION['manager']['id']));

	    if ( $_GET['do'] == 'filter' )
	    {
		unset($_SESSION['filter']['customer_list']);

		foreach ( $_GET as $key => $value )
		{
		    if ( $key == 'action' || $key == 'do' || $key == 'page' || ($value=='') ) { continue; }
		    $_SESSION['filter']['customer_list'][$key] = $value;
		}

	    }

// Фильтр-исключение: проверка флажков удаленных клиентов
	    if ( $_SESSION['filter']['customer_list']['show_deleted'] == 1 )
	    {
		if ( $_SESSION['filter']['customer_list']['only_deleted'] == 1 )
		    $customer->addFilter('`is_deleted` IS NOT NULL');
	    }
	    else
		$customer->addFilter('`is_deleted` IS NULL');

	    if ( !empty($_SESSION['filter']['customer_list']['create_date_begin']) && !empty($_SESSION['filter']['customer_list']['create_date_stop']) )
		$customer->addFilter(sprintf('`create_date` BETWEEN \'%s\' AND \'%s\'',mysql_escape_string($_SESSION['filter']['customer_list']['create_date_begin']),mysql_escape_string($_SESSION['filter']['customer_list']['create_date_end'])));

	    elseif ( !empty($_SESSION['filter']['customer_list']['create_date_begin']) )
		$customer->addFilter(sprintf('`create_date` > \'%s\'',mysql_escape_string($_SESSION['filter']['customer_list']['create_date_begin'])));

	    elseif ( !empty($_SESSION['filter']['customer_list']['create_date_end']) )
		$customer->addFilter(sprintf('`create_date` < \'%s\'',mysql_escape_string($_SESSION['filter']['customer_list']['create_date_end'])));

	    if ( is_numeric($_GET['page']) )
		$_SESSION['pager']['customer_list'] = $_GET['page'];


	    $customer->page($_SESSION['pager']['customer_list']); // Присваивание номера страницы
	    $customer->fields($_SESSION['manager']['options']['fields']['customer_list']);
	    $customer->addFilter($_SESSION['filter']['customer_list']);

	    $customer->_smarty->assign('executives',$executive);

	    $customer->getList()->show();
	    break;

/*
########################
    ОТПРАВКА ДОКУМЕНТОВ (создание очереди)
########################
*/
	case	'document.send':
/*
	    $document = new DocTTK;

	    if ( is_numeric($_GET['dateYear']) && is_numeric($_GET['dateMonth']) )
	    {
		$startDate = sprintf('%04d-%02d-01', $_GET['dateYear'], $_GET['dateMonth']);
		$document->setPeriod($startDate,false);
	    }

	    if ( is_numeric($_GET['customer']) )
	    {
	        $document->setCustomer($_GET['customer']);
	    }
	    else
	    if ( is_array($_SESSION['select']['customer']) && sizeof(array_keys($_SESSION['select']['customer']))>0 )
	    {
		$document->setCustomer(array_keys($_SESSION['select']['customer']));
	    }

	    foreach ( $document->getList() as $d )
	    {
		$account[$d['account_id']][] = array('id'=>$d['id'],'filename'=>$d['filename'],'path'=>$d['path']);
	    }

	    foreach ( $account as $id => $files )
	    {
		$query = sprintf('INSERT INTO `mail_queue` (`account_id`,`document`,`create_date`,`start_doc_date`,`stop_doc_date`) VALUES (%d,\'%s\',NOW(),\'%s\',CONCAT(LAST_DAY(DATE(\'%3$s\')),\' 23:59:59\'))',$id,json_encode(array('attach'=>$files)),$startDate);
		mysql_query($query);
	    }
*/
	    $invoice = new Invoice;

	    $customer = array_keys($_SESSION['select']['customer']);
	    $executive= $_GET['executive'];

	    $query = sprintf
	    (
		'SELECT * FROM `invoice`'
		.' JOIN `contract` ON `contract`.`id`=`invoice`.`contract_id`'
		.' JOIN `executive` ON `executive`.`id`=`contract`.`executive_id`'
		.' JOIN `customer` ON `customer`.`account_id`=`contract`.`account_id`'
		.' WHERE `invoice`.`date` BETWEEN \'%1$04d-%2$02d-01\' AND LAST_DAY(\'%1$04d-%2$02d-01\')'
		    .' AND `customer`.`id` IN (%3$s)'
		    .' AND `contract`.`executive_id` IN (%4$s)'
		    .' AND `invoice`.`status`=1',
		$_GET['dateYear'],
		$_GET['dateMonth'],
		implode(',',$customer),
		implode(',',$executive)
	    );

	    if ( $result = $invoice->_doQuery($query) )
	    {
		while ( $row = mysql_fetch_assoc($result) )
		{
		    if ( is_file(sprintf('%s/%s',Path_files,$row['account'])) )
			$docs[$row['account_id']][] = array('path'=>sprintf('%s/%s',Path_files,$row['account']));

		    if ( is_file(sprintf('%s/%s',Path_files,$row['act'])) )
			$docs[$row['account_id']][] = array('path'=>sprintf('%s/%s',Path_files,$row['act']));

		    if ( is_file(sprintf('%s/%s',Path_files,$row['invoice'])) )
			$docs[$row['account_id']][] = array('path'=>sprintf('%s/%s',Path_files,$row['invoice']));

		    if ( $_GET['detail'] == 'on' && is_file(sprintf('%s/%s',Path_files,$row['detail'])) )
			$docs[$row['account_id']][] = array('path'=>sprintf('%s/%s',Path_files,$row['detail']));
		}

		foreach ( $docs as $account_id => $files )
		{
		    $invoice->_doQuery(sprintf('INSERT INTO `mail_queue` (`document`,`create_date`,`account_id`,`start_doc_date`,`stop_doc_date`) VALUES (\'%1$s\',NOW(),%2$d,\'%3$04d-%4$02d-01\',LAST_DAY(\'%3$04d-%4$02d-01\'))',json_encode(array('attach'=>$files)),$account_id,$_GET['dateYear'],$_GET['dateMonth']));
		}
	    }

	    echo mysql_error();

	    echo 'Очередь создана. <a href="javascript:history.back();">назад</a>';
	    break;

	case	'document.make':
	    $queue = new InvoiceQueue;
	    $customer = new Customer;

	    foreach ( $_SESSION['select']['customer'] as $id => $value )
	    {
		$queue->insert
		(
		    array
		    (
			'`account_id`'	=> $customer->accountById($id),
			'`create_date`'	=> 'NOW()',
			'`from_data`'	=> '\''.$_GET['make_date'].'\''
		    )
		);

		#echo $queue->_query."<br/>";
	    }

	    echo 'Добавлено в очередь. <a href="javascript:history.back();">назад</a>';
	    break;

/*
########################
    РАБОТА С КЛИЕНТОМ(-АМИ)
########################
*/
	case	'customer':
	    $customer = new Customer;

	    if ( is_numeric($_GET['id']) )
	    {
	    }
	    elseif ( !empty($_GET['do']) )
	    {
		switch($_GET['do'])
		{
		    case	'select':
			if ( is_numeric($_GET['customer']) )
			{
			    $_SESSION['select']['customer'][$_GET['customer']] = 1;
			}
			else
			{
			    $customer->addFilter($_SESSION['filter']['customer_list']);
			    $customer->setLimit(9999);

			    foreach ( $customer->getList() as $c )
			    {
				$_SESSION['select']['customer'][$c['id']] = 1;
			    }
			}

			print json_encode(array('code'=>200));
			break;

		    case	'deselect':
			if ( is_numeric($_GET['customer']) )
			{
			    unset($_SESSION['select']['customer'][$_GET['customer']]);
			}
			else
			{
			    unset($_SESSION['select']['customer']);
			}

			print json_encode(array('code'=>200));
			break;
		}
	    }
	    break;

/*
########################
    ПРОСМОТР/РЕДАКТИРОВАНИЕ КЛИЕНТА
########################
*/
	case	'customer.edit':
	case	'customer.view':
	case	'customer.new':
	    if ( is_numeric($_GET['parent_id']) )
	    {
		if ( $customer = mysql_fetch_assoc(mysql_query(sprintf('SELECT * FROM `customer` WHERE `id`=%d AND `is_deleted` IS NULL',$_GET['parent_id']))) )
		{
		    mysql_query('START TRANSACTION');
		    mysql_query('INSERT INTO `account` SET `saas_id`=1');

		    #echo "customer[account_id]=".$customer['account_id']."\n";

		    if ( $customer['account_id'] = mysql_insert_id() )
		    {
				unset
				(
				    $customer['id'],
				    $customer['email'],
				    $customer['password']
				);

				$customer['customer_name'] = sprintf('%s [%d]',$customer['customer_name'],$customer['account_id']);
				$customer['parent'] = $_GET['parent_id'];

				foreach ( $customer as $key => $value )
				{
				    if ( empty($value) )
					$customer[$key] = 'NULL';
				    elseif ( !is_numeric($value) )
					$customer[$key] = sprintf('\'%s\'',mysql_escape_string($value));
				}

				$customer['create_date'] = 'NOW()';
				$q = sprintf('INSERT INTO `customer` (%s) VALUES (%s)',implode(',',array_keys($customer)),implode(',',array_values($customer)));

				if ( mysql_query($q) )
				    if ( $customer_id = mysql_insert_id() )
				    {
					mysql_query(sprintf('INSERT INTO `arbitrary_field` (`customer_id`,`field_name_id`,`value`) SELECT %d,`field_name_id`,`value` FROM `arbitrary_field` WHERE `customer_id`=%d',$customer_id,$_GET['parent_id']));
					mysql_query(sprintf('UPDATE `customer` SET `is_deleted`=NOW() WHERE `id`=%d',$_GET['parent_id']));
					mysql_query('COMMIT');
					header(sprintf('Location: customer-edit.php?id=%d',$customer_id));
				    } else die('x');
				else die(mysql_error());
		    }
		} else die('parent customer not found');
		exit();
	    }

	    $ph_r = new DB;
	    $ph_r->_query = 'SELECT * FROM `phone_rate` ORDER BY `rate_name`';

	    $smarty->assign('phone_rates', $ph_r->_getDataArray());

	    if ( ($_GET['action'] == 'customer.edit') || ($_GET['action'] == 'customer.view') )
	    {
		if ( is_numeric($_GET['id']) )
		{
		    $result = mysql_query('SELECT `c`.*,`p`.`customer_name` AS `parent_name` FROM `customer` c LEFT OUTER JOIN `customer` p ON `c`.`parent`=`p`.`id` WHERE `c`.`id`='.$_GET['id']);
		    if ( mysql_affected_rows()==1 )
		    {
			$customer = mysql_fetch_assoc($result);

// Все пустые (и равные нулю) значения преобразуем в пустую строку. Для "красоты"
			foreach ( $customer as $key => $value )
			{
			    if ( empty($customer[$key]) )
			    {
				$customer[$key] = '';
			    }
			}
			$smarty->assign('customer',$customer);

			#echo "аккаунт_id=".$customer['account_id'];@


			$result = mysql_query('SELECT * FROM `account` WHERE `id`='.$customer['account_id']);
			if ( mysql_affected_rows()==1 )
			{
			    $account = mysql_fetch_assoc($result);
			    $smarty->assign('account',$account);

// Список договоров
			    $result = mysql_query(sprintf('SELECT `c`.*,`e`.`executive_name` FROM `contract` c LEFT JOIN `executive` e ON `e`.`id`=`c`.`executive_id` WHERE `c`.`account_id`=%d ORDER BY `c`.`id` ASC',$account['id']));
//			    $result = mysql_query(sprintf('SELECT * FROM `contract` WHERE `account_id`=%d ORDER BY `id` ASC',$account['id']));
			    if ( $result )
			    {
				while ( $row = mysql_fetch_assoc($result) )
				{
				    $contract[] = $row;
				}
				$smarty->assign('contracts_total',sizeof($contract));
				$smarty->assign('contracts',$contract);
			    }

// Дополнительные поля
			    $result = mysql_query(sprintf('SELECT *,`arbitrary_field`.`id` AS `field_id` FROM `arbitrary_field` LEFT OUTER JOIN `field_name` ON `field_name`.`id`=`arbitrary_field`.`field_name_id` WHERE `customer_id`=%d ORDER BY `arbitrary_field`.`id` ASC',$customer['id']));
			    if ( $result )
			    {
				while ( $row = mysql_fetch_assoc($result) )
				{
				    $arbitrary_field[] = $row;
				}
//				$smarty->assign('contracts_total',sizeof($contract));
				$smarty->assign('arbitrary_fields',$arbitrary_field);
			    }

// Список услуг


			    $result = mysql_query
			    (
				sprintf
				(
				    'SELECT *,`service`.`id` AS `srv_id`,`city_uplink`.`name` AS city_name,`zona_mobile_uplink`.`name` AS `zona_mobile_name`,`zona_mobile_uplink_reserve`.`name` AS `zona_mobile_name_reserve_name`,'
				    .' `zona_stationary_uplink`.name AS `zona_stationary_name`,`zona_stationary_uplink_reserve`.`name` AS `zona_stationary_uplink_reserve_name`,`long_distance_uplink`.`name` AS `long_distance_name`,`long_distance_uplink_reserve`.`name` AS `long_distance_name_reserve`,'
				    .' `international_uplink`.`name` AS `international_name`,`international_uplink_reserve`.`name` AS `international_reserve_name` FROM `service`'
					.' JOIN `service_name` ON `service_name`.`id`=`service`.`service_name_id`'
					.' JOIN `executive` ON `executive`.`id`=`service`.`executive_id`'
					.' LEFT JOIN `contract` ON `contract`.`id` = `service`.`contract_id`'
					.' LEFT JOIN `service_phone_number` ON `service`.`id`=`service_phone_number`.`service_id`'
					.' LEFT JOIN `phone_rate` ON `phone_rate`.`id`=`service_phone_number`.`phone_rate_id`'
					.' LEFT JOIN `voip_service` ON `voip_service`.`service_id` = `service`.`id`'
					.' LEFT JOIN `city_uplink` ON `city_uplink`.`id` = `voip_service`.`city_uplink_id`'
					.' LEFT JOIN `zona_mobile_uplink` ON `zona_mobile_uplink`.`id` = `voip_service`.`zona_mobile_uplink_id`'
					.' LEFT JOIN `zona_mobile_uplink` `zona_mobile_uplink_reserve` ON `zona_mobile_uplink_reserve`.`id` = `voip_service`.`zona_mobile_uplink_reserve_id`'
					.' LEFT JOIN `zona_stationary_uplink` ON `zona_stationary_uplink`.`id` = `voip_service`.`zona_stationary_uplink_id`'
					.' LEFT JOIN `zona_stationary_uplink` `zona_stationary_uplink_reserve` ON `zona_stationary_uplink_reserve`.`id` = `voip_service`.`zona_stationary_uplink_reserve_id`'
					.' LEFT JOIN `long_distance_uplink` ON `long_distance_uplink`.`id` = `voip_service`.`long_distance_uplink_id`'
					.' LEFT JOIN `long_distance_uplink` `long_distance_uplink_reserve` ON `long_distance_uplink_reserve`.`id` = `voip_service`.`long_distance_uplink_reserve_id`'
					.' LEFT JOIN `international_uplink` ON `international_uplink`.`id` = `voip_service`.`international_uplink_id`'
					.' LEFT JOIN `international_uplink` `international_uplink_reserve` ON `international_uplink_reserve`.`id` = `voip_service`.`international_uplink_reserve_id`'
					.' WHERE `service`.`account_id`=%d ORDER BY `service`.`id`,`service`.`completed` ASC',
				    $account['id']
				)
			    );


			    if ( $result )
			    {
				while ( $row = mysql_fetch_assoc($result) )
				{
				    $query = sprintf
				    (
					'SELECT'
					    .' CONCAT(SUBSTRING_INDEX(sum(det.cost),\'.\',1),\',\',SUBSTRING_INDEX(sum(det.cost),\'.\',-1)) as cost'
					.' FROM detalisation det'
					.' JOIN service_phone_number spn ON det.service_phone_number_id = spn.id'
					.' JOIN service ser ON ser.id = spn.service_id'
					.' JOIN phone_direction pd ON det.phone_direction_id = pd.id'
					.' WHERE ser.id=%d'
					    .' AND date BETWEEN DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1 MONTH),\'%%Y-%%m-01\') AND DATE_SUB(DATE_FORMAT(NOW(),\'%%Y-%%m-01\'), INTERVAL 1 SECOND)', // CONCAT(YEAR(Now()-INTERVAL 1 MONTH),'-',MONTH(Now()-INTERVAL 1 MONTH),'-',1) and LAST_DAY(Now()-INTERVAL 1 MONTH)+INTERVAL 1 DAY;'
					$row['srv_id']
				    ); //die($query);

				    if ( $last_cost = mysql_fetch_array(mysql_query($query)) ) { $row['last_cost'] = $last_cost[0]; }

				    $service[] = $row;
				}
				$smarty->assign('services',$service);
			    }

			    $result = mysql_query(sprintf('SELECT * FROM `contract` WHERE `account_id`='.$account['id']));
				while( $row = mysql_fetch_assoc($result) )
				{
					$contract_number[] = $row;
				}
				$smarty->assign('contract_numbers',$contract_number);


// Список обращений и задач
			    $result = mysql_query('SELECT * FROM `treatment_subscriber` WHERE `account_id`='.$account['id'].' ORDER BY `date_time` DESC');
			    while ( $row = mysql_fetch_assoc($result) )
			    {
				$treatment[] = $row;
			    }
			    $smarty->assign('treatments',$treatment);

// Список контактов
			    $result = mysql_query('SELECT * FROM `contact` WHERE `account_id`='.$account['id']);
			    while ( $row = mysql_fetch_assoc($result) )
			    {
				$contact[] = $row;
			    }
			    $smarty->assign('contacts',$contact);

/*
    Блок определения фильтров для документов
*/
			    $year = date('Y');

			    if ( is_numeric($_GET['docStart_Year']) && is_numeric($_GET['docStart_Month']) && is_numeric($_GET['docEnd_Year']) && is_numeric($_GET['docEnd_Month']))
			    {
				$filter = sprintf('AND `document_date` BETWEEN \'%04d-%02d-01 00:00:00\' AND CONCAT(LAST_DAY(\'%04d-%02d-01\'),\' 23:59:59\')',$_GET['docStart_Year'],$_GET['docStart_Month'],$_GET['docEnd_Year'],$_GET['docEnd_Month']);
				$smarty->assign('by_period',1);
			    }
			    else
			    if ( !is_numeric($_GET['quarter']) )
			    {
				$result = mysql_fetch_array(mysql_query('SELECT QUARTER(NOW())'));
				$q_index= $result[0];
				$smarty->assign('quarter',$q_index);
			    }
			    else
			    {
				$q_index = $_GET['quarter'];
			    }

// Определение текущего квартала:

/*
			    $quarter = array
			    (
				'1'	=> sprintf('BETWEEN \'%1$04d-01-01 00:00:00\' AND CONCAT(LAST_DAY(DATE_ADD(\'%1$04d-01-01\', INTERVAL 3 MONTH)),\' 23:59:59\')',$year),
				'2'	=> sprintf('BETWEEN \'%1$04d-04-01 00:00:00\' AND CONCAT(LAST_DAY(DATE_ADD(\'%1$04d-04-01\', INTERVAL 3 MONTH)),\' 23:59:59\')',$year),
				'3'	=> sprintf('BETWEEN \'%1$04d-07-01 00:00:00\' AND CONCAT(LAST_DAY(DATE_ADD(\'%1$04d-07-01\', INTERVAL 3 MONTH)),\' 23:59:59\')',$year),
				'4'	=> sprintf('BETWEEN \'%1$04d-10-01 00:00:00\' AND CONCAT(LAST_DAY(DATE_ADD(\'%1$04d-10-01\', INTERVAL 3 MONTH)),\' 23:59:59\')',$year),
			    );
*/

			    if ( !$filter )
			    {
				$filter = 'AND ((YEAR(`document_date`)=YEAR(NOW()) AND QUARTER(`document_date`)=QUARTER(NOW())) OR (`document_date` BETWEEN DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1 MONTH),\'%Y-%m-01\') AND CONCAT(LAST_DAY(DATE_SUB(NOW(), INTERVAL 1 MONTH)),\' 23:59:59\')))';
			    }

/*
    Блок выборки документов
*/

// Общие документы
			    $result = mysql_query(sprintf('SELECT * FROM `document` WHERE `account_id`='.$account['id'].' AND `type`=\'ordinary\' ORDER BY `document_date` DESC'));
			    while ( $row = mysql_fetch_assoc($result) )
			    {
				$doc_regular[] = $row;
			    }
			    $smarty->assign('docs_regular',$doc_regular);

				// Договора
				$result = mysql_query(sprintf('SELECT * FROM `contract` WHERE `account_id`='.$account['id']));
				while( $row = mysql_fetch_assoc($result) )
				{
					$contract_number[] = $row;
				}
				$smarty->assign('contract_numbers',$contract_number);


// Расчетные документы
			    $invoice = new Invoice;

			    $query = sprintf
			    (
				'SELECT *,`invoice`.`id` AS `id` FROM `invoice`'
				.' JOIN `contract` ON `contract`.`id`=`invoice`.`contract_id`'
				.' WHERE `contract`.`account_id`=%d'
				.' ORDER BY `invoice`.`date` ASC',
				$account['id']
			    );

			    if ( $result = $invoice->_doQuery($query) )
			    {
				while ( $row = mysql_fetch_assoc($result) )
				{
				    $invoices[$row['executive_id']][] = $row;
				}

				$smarty->assign('invoices',$invoices);
			    }

/***********************************************
// Документы ТТК
			    $result = mysql_query(sprintf('SELECT * FROM `document` WHERE `account_id`='.$account['id'].' AND `type`=\'ttk\' %s ORDER BY `document_date` DESC', $filter));
			    while ( $row = mysql_fetch_assoc($result) )
			    {
				$doc_ttk[] = $row;
			    }
			    $smarty->assign('docs_ttk',$doc_ttk);

// Счета РЕГИОН
			    $result = mysql_query(sprintf('SELECT * FROM `document` WHERE `account_id`='.$account['id'].' AND `type`=\'inv_region\' ORDER BY `document_date` DESC',$filter));
			    while ( $row = mysql_fetch_assoc($result) )
			    {
				$doc_rtk[] = $row;
			    }
			    $smarty->assign('docs_rtk',$doc_rtk);


// Счета ИНЛАЙН
			    $result = mysql_query(sprintf('SELECT * FROM `document` WHERE `account_id`='.$account['id'].' AND `type`=\'inv_inlain\' ORDER BY `document_date` DESC',$filter));
			    while ( $row = mysql_fetch_assoc($result) )
			    {
				$doc_inlain[] = $row;
			    }
			    $smarty->assign('docs_inline',$doc_inlain);
************************************************/
			}
		    }
		}
	    }

	    $result = mysql_query('SELECT * FROM `group` ORDER BY `group_name`');
	    while ( $row = mysql_fetch_assoc($result) )
	    {
		$groups[] = $row;
	    }

	    $result = mysql_query('SELECT * FROM `status` ORDER BY `status_name`');
	    while ( $row = mysql_fetch_assoc($result) )
	    {
		$statuses[] = $row;
	    }

	    $smarty->assign('groups',$groups);
	    $smarty->assign('statuses',$statuses);

	    $smarty->assign('session',$_SESSION);
	    $smarty->display('admin/customer.html');
	    break;

/*
    Блок удаления клиента
    Фактически клиент остаётся в базе с флагом is_deleted=1
*/
	case	'customer.delete':
	    if ( isset($_GET['id']) )
	    {
		mysql_query('UPDATE `customer` SET `is_deleted`=NOW() WHERE `id`='.$_GET['id']);
	    }
	    header('Location: '.$_SERVER['HTTP_REFERER']);
	    break;

	case	'arbitrary.delete':
	    if ( is_numeric($_GET['id']) )
	    {
		mysql_query('DELETE FROM `arbitrary_field` WHERE `id`='.$_GET['id']);
	    }
	    header('Location: '.$_SERVER['HTTP_REFERER']);
	    break;

	case	'service.delete':
	    if ( is_numeric($_GET['id']) )
	    {
		mysql_query('DELETE FROM `service` WHERE `id`='.$_GET['id']);
	    }

	    if ( $err = mysql_error() ) { die($err); }

	    header('Location: '.$_SERVER['HTTP_REFERER'].'#services');
	    break;

/*
    Блок удаления документа
    Документ удаляется из БД и с файловой системы без возможности восстановления
*/
	case	'document.delete':
	    if ( isset($_GET['id']) )
	    {
		$file = mysql_fetch_array(mysql_query('SELECT `path` FROM `document` WHERE `id`='.$_GET['id']));
		if ( file_exists($file[0]) ) { unlink($file[0]); }
		mysql_query('DELETE FROM `document` WHERE `id`='.$_GET['id']);
	    }
	    header('Location: '.$_SERVER['HTTP_REFERER'].'#document');
	    break;

/*
    Блок удаления контактного лица
    Удаляется из БД безвозвратно
*/
	case	'contact.delete':
	    if ( isset($_GET['id']) )
	    {
		mysql_query('DELETE FROM `contact` WHERE `id`='.$_GET['id']);
	    }
	    header('Location: '.$_SERVER['HTTP_REFERER'].'#contact');
	    break;

/*
    Блок удаления договора
    Удаляется из БД безвозвратно
*/
	case	'contract.delete':
	    if ( isset($_GET['id']) )
	    {
		mysql_query('DELETE FROM `contract` WHERE `id`='.$_GET['id']);
	    }
	    header('Location: '.$_SERVER['HTTP_REFERER']);
	    break;

	case	'doc.print':
	    if ( is_numeric($_GET['account_id']) )
	    {
		$result = mysql_query('SELECT * FROM `account` WHERE `id`='.$_GET['account_id']);
		if ( mysql_affected_rows()==1 )
		{
		    $account = mysql_fetch_assoc($result);

		    $customer = mysql_fetch_assoc(mysql_query('SELECT * FROM `customer` WHERE `account_id`='.$account['id']));
		    $contract = mysql_fetch_assoc(mysql_query('SELECT * FROM `contract` WHERE `account_id`='.$account['id']));
		    $contact = mysql_fetch_assoc(mysql_query('SELECT * FROM `contact` WHERE `account_id`='.$account['id']));

		    $smarty->assign('customer',$customer);
		    $smarty->assign('contract',$contract);
		    $smarty->assign('contact',$contact);
		}
		else { die ('no data'); }
	    }
	    else { die ('no account'); }

	    if ( is_numeric($_GET['executive_id']) )
	    {
		$template = sprintf('admin/print/%d/%s.html',$_GET['executive_id'],$_GET['type']);
		if ( file_exists($smarty->template_dir.'/'.$template) )
		{
		    $smarty->display($template);
		}
		else
		{
		    die('Шаблон для этого исполнителя и/или документа не найден!');
		}
	    }
	    break;

/*
    Блок работы со справочниками
*/
	case	'dictionary2':
	    if ( !$_SESSION['manager']['is_admin'] ) { die('Доступ запрещён'); }

	    if ( !empty($_GET['table']) )
	    {
		switch($_GET['table'])
		{
		    case	'status':
			$dictionary = new Status;
			break;

		    case	'group':
			$dictionary = new Group;
			break;

		    case	'manager':
			$dictionary = new Manager;
			break;

		    case	'service_name':
			$dictionary = new ServiceName;
			break;

		    case	'field_name':
			$dictionary = new FieldName;
			break;

		    case	'executive':
			$dictionary = new Executive;
			break;
		}

		if ( $_GET['do'] == 'init' )
		{
		    print json_encode( $dictionary->jqGridOptions );
		    exit();
		}
		else
		if ( $_GET['do'] == 'getData' )
		{
		    print json_encode( $dictionary->jqGridArray($_GET['page'],$_GET['rows'],array($_GET['sidx'],$_GET['sord'])) );
		    exit();
		}
	    }

	    $smarty->display('admin/dictionary2.html');
	    break;

	case	'dictionaries':
	    switch ( $_REQUEST['name'] )
	    {
		case	'manager':
		    if ( $_REQUEST['format'] == 'xml' )
		    {
			header('Content-Type: text/xml');

			$xml = new SimpleXMLElement('<manager/>');

			error_log(serialize($_REQUEST));

			if ( is_numeric($_REQUEST['id']) )
			{
			    if ( $_SERVER['REQUEST_METHOD'] == 'POST' )
			    {
				if ( !empty($_REQUEST['login']) )
				    $field[] = sprintf('`login`=\'%s\'',mysql_escape_string($_REQUEST['login']));

				if ( !empty($_REQUEST['manager_name']) )
				    $field[] = sprintf('`manager_name`=\'%s\'',mysql_escape_string($_REQUEST['manager_name']));

				if ( !empty($_REQUEST['password']) )
				    $field[] = sprintf('`password`=\'%s\'',mysql_escape_string($_REQUEST['password']));

				if ( $_REQUEST['internal_number'] != '' )
				    $field[] = sprintf('`internal_number`=\'%s\'',mysql_escape_string($_REQUEST['internal_number']));
				else
				    $field[] = '`internal_number`=NULL';

				if ( !empty($_REQUEST['start_time']) )
				    $field[] = sprintf('`start_time`=\'%s\'',mysql_escape_string($_REQUEST['start_time']));
				else
				    $field[] = '`start_time`=NULL';

				if ( $_REQUEST['is_admin'] == 'on' )
				    $field[] = '`is_admin`=1';
				else
				    $field[] = '`is_admin`=0';

				if ( $_REQUEST['is_deleted'] == 'on' )
				    $field[] = '`is_deleted`=1';
				else
				    $field[] = '`is_deleted`=0';

				if ( is_numeric($_REQUEST['id']) )
				    $query = sprintf('UPDATE `manager` SET %s WHERE `id`=\'%s\'',implode(',',$field),$_REQUEST['id']);
				else
				    $query = sprintf('INSERT INTO `manager` %s',implode(',',$field));

				error_log($query);

				if ( mysql_query($query) )
				    $xml->addChild('result','OK')->addAttribute('code',200);
				else
				    $xml->addChild('result',mysql_error())->addAttribute('code',500);
			    }
			    elseif ( $result = mysql_query(sprintf('SELECT * FROM `manager` WHERE `id`=%d',$_REQUEST['id'])) )
				if ( $manager = mysql_fetch_assoc($result) )
				    foreach ( array_keys($manager) as $key )
					$xml->addChild('field',$manager[$key])->addAttribute('name',$key);
			}
			elseif ( is_array($_REQUEST['managers']) )
			{
			    switch ( $_REQUEST['do'] )
			    {
				case	'set_time':
				    if ( mysql_query(sprintf('UPDATE `manager` SET `start_time`=\'%s\' WHERE `id` IN (%s)',$_REQUEST['start_time'],implode(',',$_REQUEST['managers']))) )
					$xml->addChild('result','OK')->addAttribute('status',200);
				    else
					$xml->addChild('result',mysql_error())->addAttribute('status',500);
				    break;

				case	'delete':
				    if ( mysql_query(sprintf('UPDATE `manager` SET `is_deleted`=1 WHERE `id` IN (%s)',implode(',',$_REQUEST['managers']))) )
					$xml->addChild('result','OK')->addAttribute('status',200);
				    else
					$xml->addChild('result',mysql_error())->addAttribute('status',500);
				    break;
				    break;
			    }
			}
			else
			{
			    $xml->addAttribute('name','manager');

			    if ( $result = mysql_query(sprintf('SELECT * FROM `manager` WHERE `is_deleted`=%d ORDER BY `manager_name`',$_REQUEST['show_deleted'])) )
			    {
				$rows = $xml->addChild('rows');

				while ( $row = mysql_fetch_assoc($result) )
				{
				    $r = $rows->addChild('row');

				    $r->addAttribute('id',$row['id']);
				    $r->addChild('cell',strtolower($row['login']))->addAttribute('name','login');
				    $r->addChild('cell',$row['manager_name'])->addAttribute('name','manager_name');
				    $r->addChild('cell',$row['internal_number'])->addAttribute('name','internal_number');
				    $r->addChild('cell',$row['is_admin'])->addAttribute('name','is_admin');
				    $r->addChild('cell',$row['is_deleted'])->addAttribute('name','is_deleted');
				}
			    }
			}

			exit($xml->asXML());
		    }
		    break;

		case	'fine_settings':
		    if ( $_REQUEST['format'] == 'xml' )
		    {
			header('Content-Type: text/xml');

			$xml = new SimpleXMLElement('<fine_settings/>');

			if ( $_SERVER['REQUEST_METHOD'] == 'POST' )
			{
			    if ( $_REQUEST['do'] == 'add' )
				if ( mysql_query(sprintf('REPLACE INTO `fine_settings` (`delay_start`,`delay_stop`,`cost`) VALUES (%d,%d,\'%0.2f\')',$_REQUEST['delay_start'],$_REQUEST['delay_stop'],$_REQUEST['cost'])) )
				    $xml->addChild('result','OK')->addAttribute('status',200);
				else
				    $xml->addChild('result',mysql_error())->addAttribute('status',500);
			    elseif ( !empty($_REQUEST['id']) )
			    {
				mysql_query(sprintf('UPDATE `fine_settings` SET `cost`=%d WHERE CONCAT(`delay_start`,\'-\',`delay_stop`)=\'%s\'',$_REQUEST['cost'],mysql_escape_string($_REQUEST['id'])));
				exit($xml->asXML());
			    }
			}
			elseif ( $_REQUEST['do'] == 'delete' )
			    if ( mysql_query(sprintf('DELETE FROM `fine_settings` WHERE CONCAT(`delay_start`,\'-\',`delay_stop`)=\'%s\'',$_REQUEST['id'])) )
				$xml->addChild('result','OK')->addAttribute('status',200);
			    else
				$xml->addChild('result',mysql_error())->addAttribute('status',500);
			elseif ( $result = mysql_query('SELECT * FROM `fine_settings` ORDER BY `delay_start` ASC') )
			{
			    $rows = $xml->addChild('rows');

			    while ( $row = mysql_fetch_assoc($result) )
			    {
				$r = $rows->addChild('row');
				$r->addAttribute('id',sprintf('%d-%d',$row['delay_start'],$row['delay_stop']));

				foreach ( array_keys($row) as $key )
				    $r->addChild('cell',$row[$key])->addAttribute('name',$key);
			    }
			}

			exit($xml->asXML());
		    }
		    break;
	    };

	    $smarty->display('admin/dictionary_2.0.html');
	    break;

	case	'dictionary':
	    if ( !$_SESSION['manager']['is_admin'] ) { die('Доступ запрещён'); }

// Указываем список таблиц, являющихся справочниками (Формат: 'table_name'=>'Название справочника')
	    $dictionary = array
	    (
		'group'		=> 'Группы',
		'status'	=> 'Статусы',
		'manager'	=> 'Сотрудники',
		'service_name'	=> 'Услуги',
		'field_name'	=> 'Дополнительные поля',
		'executive'	=> 'Исполнители по услугам',
	    );

// Указываем заголовки полей таблиц.
// Если заголовок не определён, то в интерфейсе будет вывдено название поля "as is" из БД
// Формат: $title['table_name']['field_name'] = 'Заголовок поля'
	    $title = array
	    (
		'service_name'	=> array
		(
		    'service_name'	=> 'Наименование услуги',
		),
		'field_name'	=> array
		(
		    'field_name'	=> 'Название поля',
		),
		'group'		=> array
		(
		    'group_name'	=> 'Группа',
		),
		'status'		=> array
		(
		    'status_name'	=> 'Статус',
		),
		'manager'		=> array
		(
		    'manager_name'	=> 'Имя',
		    'login'		=> 'Логин',
		    'password'		=> 'Пароль',
		    'is_admin'		=> 'Админ (1=да/0=нет)',
		    'options'		=> 'Доп.опции (не менять!)',
		    'internal_number'	=> 'Внутр.номер',
		),
		'executive'		=> array
		(
		    'executive_name'		=> 'Наименование'
		),
	    );

// Определяем, выбран ли справочник
	    if ( isset($_GET['table']) && isset($dictionary[$_GET['table']]) )
	    {
// Определяем, переданы ли новые данные с формы
		if ( sizeof($_POST)>1 )
		{
		    foreach ( $_POST as $key=>$value )
		    {
			if ( ($key=='id')||($key=='table') ) { continue; }
			$field[] = sprintf('`%s`=\'%s\'',mysql_escape_string($key),mysql_escape_string($value));
		    }

		    if ( isset($_POST['id']) )
		    {
			$query = sprintf('UPDATE `%s` SET %s WHERE `id`=%d',$_POST['table'],implode(',',$field),mysql_escape_string($_POST['id']));
			mysql_query($query)||die(mysql_error());
			header('Location: '.$_SERVER['HTTP_REFERER']);
		    }
		    else
		    {
			$query = sprintf('INSERT INTO `%s` SET %s',$_POST['table'],implode(',',$field));
			mysql_query($query)||die(mysql_error());
			header('Location: '.$_SERVER['HTTP_REFERER']);
		    }

		    exit();
		}

// Пришёл запрос на удаление/инфо?
		if ( $_GET['do']=='delete' )
		{
		    switch($_GET['table'])
		    {
			case	'status':
			    $query = sprintf('SELECT COUNT(*) FROM `customer` WHERE `status_id`=%d',mysql_escape_string($_GET['id']));
			    break;

			case	'group':
			    $query = sprintf('SELECT COUNT(*) FROM `customer` WHERE `group_id`=%d',mysql_escape_string($_GET['id']));
			    break;

			default:
			    $nocheck = true;
		    }

		    if ( $nocheck )
		    {
			mysql_query(sprintf('DELETE FROM `%s` WHERE `id`=%d',$_GET['table'],$_GET['id']));
			print json_encode(array('code'=>200));
		    }
		    else
		    {
			$count = mysql_fetch_array(mysql_query($query));
			if ( $count[0]>0 )
			{
			    print json_encode(array('code'=>403));
			}
			else
			{
			    mysql_query(sprintf('DELETE FROM `%s` WHERE `id`=%d',$_GET['table'],$_GET['id']));
			    print json_encode(array('code'=>200));
			}
		    }
		    exit();
		}
		else
		if ( $_GET['do']=='get_info' )
		{
		    if ( isset($_GET['id']) )
		    {
			$object = mysql_fetch_assoc(mysql_query(sprintf('SELECT * FROM `%s` WHERE `id`=%d',$_GET['table'],$_GET['id'])));

			foreach ( array_keys($object) as $key )
			{
			    $object[$key] = stripslashes($object[$key]);
			}

			print json_encode(array('code'=>200,'titles'=>$title[$_GET['table']],'object'=>$object));
		    }
		    exit();
		}

		$smarty->assign('table',$_GET['table']);
		$smarty->assign('title',$title);

		$result = mysql_query(sprintf('DESC `%s`',$_GET['table']));
		while( $row=mysql_fetch_assoc($result) )
		{
		    $field[] = $row;
		}
		$smarty->assign('fields',$field);

		$result = mysql_query(sprintf('SELECT * FROM `%s`',$_GET['table']));
		while( $row = mysql_fetch_assoc($result) )
		{
		    $item[] = $row;
		}
		$smarty->assign('items',$item);
	    }

// Вывод списка справочников
	    $smarty->assign('dictionaries',$dictionary);
	    $smarty->display('admin/dictionary.html');
	    break;

/*
    Блок работы с необсчитанными направлениями
*/
	case	'calls':
// Если получен запрос от jqGrid
	    if ( isset($_GET['_search']) && is_numeric($_GET['nd']) )
	    {
		$data = array();

		$data['page'] = intval($_GET['page']);

		switch ( $_GET['sidx'] )
		{
		    case	'title':
			$_sord = '`pd`.`title`';
			break;

		    default:
			if ( !empty($_GET['sidx']) )
			{
			    $_sord = sprintf('`rd`.`%s`',$_GET['sidx']);
			}
			else
			{
			    $_sord = '`rd`.`date`';
			}
		}

		switch ( $_GET['mode'] )
		{
//
// ВСЕ необсчитанные записи
//
		    case	'unallocated-all';
// Считаем общее количество записей
			$cquery =
			    'SELECT COUNT(*)'
			    .' FROM `raw_data` rd'
			    .' LEFT JOIN `phone_direction` pd ON `pd`.`id`=`rd`.`phone_direction_id`';

			if ( $result = mysql_query($cquery) )
			{
			    $count = mysql_fetch_row($result);
			    $data['records'] = $count[0];
			    $data['total'] = ceil($data['records']/intval($_GET['rows']));
			}

// Делаем выборку всех записей
			$query = sprintf
			(
			    'SELECT '
				.'`rd`.`id`,'
				.'`rd`.`src`,'
				.'`rd`.`dst`,'
				.'`rd`.`date`,'
				.'`rd`.`duration`,'
				.'`pd`.`title`'
			    .' FROM `raw_data` rd'
			    .' LEFT JOIN `phone_direction` pd ON `pd`.`id`=`rd`.`phone_direction_id`'
			    .' ORDER BY %s %s'
			    .' LIMIT %d,%d',
			    $_sord,strtoupper($_GET['sord']),
			    $_GET['rows']*($data['page']-1),$_GET['rows']
			);

			if ( $result = mysql_query($query) )
			{
			    while ( $row = mysql_fetch_row($result) )
			    {
				//$row[4] = ($row[4]%60>5)?ceil($row[4]/60):floor($row[4]/60);
				$row[4] = ceil($row[4]/60);
				$data['rows'][] = array('id'=>$row[0],'cell'=>$row);
			    }
			}

			break;

		    case	'unallocated-directions':
// Считаем общее количество записей
			$cquery =
			    'SELECT COUNT(*)'
			    .' FROM `raw_data` rd'
			    .' WHERE `phone_direction_id` IS NULL';

			if ( $result = mysql_query($cquery) )
			{
			    $count = mysql_fetch_row($result);
			    $data['records'] = $count[0];
			    $data['total'] = ceil($data['records']/intval($_GET['rows']));
			}

			if ( is_numeric($_GET['phone_direction_id']) )
			{
			    $filter = sprintf('`phone_direction_id`=%d',$_GET['phone_direction_id']);
			}
			else
			{
			    $filter = '`phone_direction_id` IS NULL';
			}

			$query = sprintf
			(
			    'SELECT `id`,`date`,`dst` FROM `raw_data` rd WHERE %s ORDER BY %s %s LIMIT %d,%d',
			    $filter,
			    $_sord,strtoupper($_GET['sord']),
			    $_GET['rows']*($data['page']-1),$_GET['rows']
			);

			if ( $result = mysql_query($query) )
			{
			    while ( $row = mysql_fetch_row($result) )
			    {
				$data['rows'][] = array('id'=>$row[0],'cell'=>$row);
			    }
			}

			break;

		    case	'unallocated-directions-rate':
			$query = sprintf
			(
			    'SELECT '
				.'`pd`.`id`,'
				.'`rd`.`dst`,'
				.'`pd`.`prefix`,'
				.'`pd`.`title`'
			    .' FROM `raw_data` rd'
			    .' JOIN `phone_direction` pd ON `pd`.`id`=`rd`.`phone_direction_id`'
			    .' WHERE `pd`.`id` != 11401'
				.' AND `rd`.`phone_direction_id` IS NOT NULL'
			    .' GROUP BY `pd`.`id`'
			    .' ORDER BY %s %s'
			    .' LIMIT %d,%d',
			    $_sord,strtoupper($_GET['sord']),
			    $_GET['rows']*($data['page']-1),$_GET['rows']
			);

//			die($query);

			if ( $result = mysql_query($query) )
			{
			    while ( $row = mysql_fetch_row($result) )
			    {
				$data['rows'][] = array('id'=>$row[0],'cell'=>$row);
			    }
			}

			break;

		    case	'unallocated-subscribers':
			$query = sprintf
			(
			    'SELECT `src`'
			    .' FROM `raw_data` rd'
			    .' WHERE (SELECT COUNT(*) FROM `service_phone_number` WHERE `phone_number`=`src`) = 0'
			    .' GROUP BY `src`'
			    .' ORDER BY %s %s'
			    .' LIMIT %d,%d',
			    $_sord,strtoupper($_GET['sord']),
			    $_GET['rows']*($data['page']-1),$_GET['rows']
			);

			if ( $result = mysql_query($query) )
			{
			    while ( $row = mysql_fetch_row($result) )
			    {
				$data['rows'][] = array('id'=>$row[0],'cell'=>$row);
			    }
			}

			break;
		}

// Возврат JSON-структуры и выход
		echo json_encode($data);
		exit();
	    }
// Если получена команда на выполнение действий
	    if ( is_string($_GET['do']) )
	    {
		$data = array();

		switch ( $_GET['do'] )
		{
		    case	'get-cost':
			if ( is_numeric($_GET['rate_id']) && is_numeric($_GET['zone_num']) )
			{
			    if ( $data['zone'] = mysql_fetch_assoc(mysql_query(sprintf('SELECT * FROM `rate_zone` WHERE `phone_rate_id`=%d AND `zone_number`=%d',$_GET['rate_id'],$_GET['zone_num']))) )
			    {
				$data['code'] = 200;
			    }
			}
			break;

		    case	'save-directions':
			if ( count($_GET)>1 && is_numeric($_GET['phone_direction_id']) )
			{
			    foreach ( $_GET as $rate_id => $zone_num )
			    {
				if ( is_numeric($rate_id) && is_numeric($zone_num) )
				{
				    mysql_query
				    (
					sprintf
					(
					    'INSERT INTO `rate_zone`'
					    .' (`phone_rate_id`,`phone_direction_id`,`zone_number`,`cost`)'
					    .' SELECT %d,%d,%d,(SELECT `cost` FROM `rate_zone` WHERE `phone_rate_id`=%1$d AND `zone_number`=%3$d ORDER BY `id` DESC LIMIT 1)',
					    $rate_id,
					    $_GET['phone_direction_id'],
					    $zone_num
					)
				    );

				    if ( $err=mysql_error() ) { die($err); }
				}
			    }

			    $data['code'] = 200;
			}
			break;

		    case	'delete': // Удаление записи о звонке
			if ( count($_GET['id'])>0 )
			{
			    mysql_query(sprintf('DELETE FROM `raw_data` WHERE `id` IN (%s)',implode(',',$_GET['id'])));
			}

			$data['code'] = 200;
			break;

		    case	'add_direction': // Добавление нового направления в справочник
			if ( is_numeric($_GET['prefix']) && !empty($_GET['name']) )
			{
			    if ( $_GET['phone_direction_id'] == 11401 && is_numeric($_GET['id']) )
			    {
				mysql_query(sprintf('UPDATE `raw_data` SET `phone_direction_id`=NULL WHERE `dst` LIKE \'%s%%\'',$_GET['prefix']));
			    }

			    $query = sprintf('INSERT INTO `phone_direction` (`prefix`,`title`) VALUES (\'%s\',\'%s\')',$_GET['prefix'],$_GET['name']);

			    mysql_query($query);

			    if ( $data['row']['id'] = mysql_insert_id() )
			    {
				$data['row']['prefix']	= $_GET['prefix'];
				$data['row']['title']	= $_GET['name'];
			    }
			    else
			    {
				$data['error']['query'] = $query;
				$data['error']['desc'] = mysql_error();
			    }
			}

			$data['code'] = 200;
			break;
		}

// Возврат JSON-структуры и выход
		echo json_encode($data);
		exit();
	    }

	    $smarty->display('admin/calls.html');
	    break;

/*
    БЛОК СОЗДАНИЯ ОЧЕРЕДИ РАССЫЛКИ
*/
	case	'mail':
	    $db = new DB;

// Получаем JSON-структуру с получателями рассылки
	    if ( $_GET['get_recipients'] == 'true' )
	    {
		$data = array();

		if ( is_array($_SESSION['select']['customer']) )
		{
// Начинаем циклический перебор выбранных клиентов
		    foreach ( $_SESSION['select']['customer'] as $customer_id => $key ) // Для каждого клиента
		    {
			if ( $result = mysql_fetch_assoc($db->_doQuery(sprintf('SELECT * FROM `customer` WHERE `id`=%d',$customer_id))) )
			{
			    $customer_name	= stripslashes($result['customer_name']);
			    $customer_id	= $result['id'];

			    $data[$customer_id]['name'] = $customer_name;

// Проверяем, похоже ли поле на корректный E-Mail
			    if ( preg_match('/@/',$result['email']) )
			    {
				$data[$customer_id]['rcpt'][] = array
				(
				    'to'	=> $customer_name,
				    'mail'	=> trim($result['email']),
				    'obj'	=> base64_encode(serialize(array
				    (
					'customer_name'	=> $customer_name,
					'customer_id'	=> $customer_id,
					'mail'		=> trim($result['email'])
				    )))
				);
			    }

// Делаем выборку всех контактов для текущего клиента
			    if ( $result = $db->_doQuery(sprintf('SELECT * FROM `contact` WHERE `account_id`=%d',$result['account_id'])) )
			    {
				while ( $row = mysql_fetch_assoc($result) ) // Для каждого контакта
				{
// Проверяем, похоже ли поле на корректный E-Mail
				    if ( preg_match('/@/',$row['email']) )
				    {
					$data[$customer_id]['rcpt'][] = array
					(
					    'to'	=> empty($row['contact_name'])?$customer_name:stripslashes($row['contact_name']),
					    'mail'	=> trim($row['email']),
					    'obj'	=> base64_encode(serialize(array
					    (
						'customer_name'	=> $customer_name,
						'customer_id'	=> $customer_id,
						'mail'		=> trim($row['email'])
					    )))
					);
				    }
				}
			    }
			}
		    }
		}

		echo json_encode($data);
		exit();
	    }
// Конец блока передачи JSON-структуры получателей

// Если получили методом POST список получателей
	    if ( is_array($_POST['recipient']) )
	    {
		if ( count($_FILES['attach'])>0 ) // Если были прикреплены файлы
		{
		    $file = array();

		    for ( $i=0; $i<count($_FILES['attach']['name']); $i++ )
		    {
			if ( $_FILES['attach']['size'][$i]>0 && is_uploaded_file($_FILES['attach']['tmp_name'][$i]) ) // Если размер файла больше 0
			{
			    $file_path = sprintf('/tmp/%s',uniqid(FALSE,TRUE)); // Генерируем новый путь для файла

			    if ( move_uploaded_file($_FILES['attach']['tmp_name'][$i],$file_path) )
			    {
				$file[] = array
				(
				    'name'	=> $_FILES['attach']['name'][$i],
				    'size'	=> $_FILES['attach']['size'][$i],
				    'path'	=> $file_path
				);
			    }
			}

			for ( $j=0; $j<count($file); $j++ )
			{
			    $file[$j]['object'] = serialize($file[$j]);
			}
		    }

		    $smarty->assign('files',$file);
		}

// Если подтвердили отправку (этап 2), переходим к созданию сообщений
		if ( $_POST['confirmed'] == 'yes' )
		{
		    require_once('swift/swift_required.php'); // Подключаем SWIFT-Mailer
		    $_POST['message'] = base64_decode($_POST['message']); // Декодируем сообщение

// Определяем тип рассылки:
		    switch ( $_POST['type'] )
		    {
/*
    ОТПРАВКА РАСЧЕТНЫХ ДОКУМЕНТОВ
*/
			case	'docs':
			    foreach ( $_POST['recipient'] as $rcpt )
			    {
				$rcpt	= unserialize(base64_decode($rcpt)); // Раскодируем получателя, и преобразовываем в массив

// Осуществляем замену ключевых слов
				$cQuery = sprintf // Запрос на выборку всех контактов по клиенту
				(
				    'SELECT '
					.'`cs`.`email`,'
					.'`cs`.`password`,'
					.'`cn`.`contact_name`,'
					.'UCASE(`cn`.`post`) as `post`'
				    .' FROM `contact` cn'
				    .' JOIN `customer` cs ON `cs`.`account_id`=`cn`.`account_id`'
				    .' WHERE `cs`.`id`=%d'
					.' AND `cn`.`post`!=\'\''
					.' AND `cn`.`post` IS NOT NULL'
					.' AND `cn`.`contact_name`!=\'\''
					.' AND `cn`.`contact_name` IS NOT NULL',
				    $rcpt['customer_id']
				);

// Устанавливаем ключевые слова

// %КИЛЕНТ% будет заменено на название организации
				$_POST['message'] = str_replace('%ЛИЧНЫЙ_КАБИНЕТ%',constant('UserCabinet_URL'),$_POST['message']);
				$_POST['message'] = str_replace('%КЛИЕНТ%',$rcpt['customer_name'],$_POST['message']);

				if ( $result = $db->_doQuery($cQuery) )
				{
				    while ( $row = mysql_fetch_assoc($result) )
				    {
// Вместо %НАЗВАНИЯ ДОЛЖНОСТИ% (например, %ДИРЕКТОР%) будет подставлено имя соответствующее этой должности (из "контактов")
					$_POST['message'] = str_replace('%ЛОГИН%',$row['email'],$_POST['message']);
					$_POST['message'] = str_replace('%ПАРОЛЬ%',$row['password'],$_POST['message']);
					$_POST['message'] = str_replace(sprintf('%%%s%%',preg_replace('/\s+/','_',trim($row['post']))),$row['contact_name'],$_POST['message']);
//					$_POST['message'] = str_replace('%ДОЛЖНОСТЬ%',$row['post'],$_POST['message']);
				    }
				}

				foreach ( $_POST['executive_id'] as $e_id )
				{
				    $message= Swift_Message::newInstance();

				    $message->setSubject(sprintf('Расчетные документы для %s',$rcpt['customer_name']));	// Тема

// Добавляем содержимое сообщения
				    $message->setCharset('utf-8');

				    if ( !empty($_POST['debug_mail']) )
					$message->setTo(array($_POST['debug_mail']=>$rcpt['customer_name']));
				    else
					if ( strlen($rcpt['customer_name']) <= 110 )
					    $message->setTo(array($rcpt['mail']=>$rcpt['customer_name']));
					else
					    $message->setTo($rcpt['mail']);

				    $dQuery = sprintf
				    (
					'SELECT '
					    .'`i`.`id`,'
					    .'`i`.`date`,'
					    .'`i`.`account`,'
					    .'`i`.`act`,'
					    .'`i`.`invoice`,'
					    .'`i`.`detail`,'
					    .'`e`.`executive_name`,'
					    .'`e`.`email_from_address`,'
					    .'`e`.`email_login`'
					.' FROM `invoice` i'
					.' JOIN `contract` ct ON `ct`.`id`=`i`.`contract_id`'
					.' JOIN `customer` cs ON `cs`.`account_id`=`ct`.`account_id`'
					.' JOIN `executive` e ON `e`.`id`=`ct`.`executive_id`'
					.' WHERE 1'
					    .' AND `i`.`date` BETWEEN \'%1$s-01\''
						.' AND DATE_SUB(DATE_ADD(\'%1$s-01\', INTERVAL 1 MONTH), INTERVAL 1 SECOND)'
					    .' AND `cs`.`id`=%2$d'
					    .' AND `ct`.`executive_id`=%3$d'
					    .' AND `e`.`email_smtp` IS NOT NULL'
					    .' AND (`e`.`email_from_address` IS NOT NULL OR `e`.`email_login` IS NOT NULL)',
					$_POST['period'],
					$rcpt['customer_id'],
					$e_id
				    );

				    error_log($dQuery);

				    if ( $result = $db->_doQuery($dQuery) )
				    {
					$doc_id = array();

					$db->_doQuery('START TRANSACTION');

					while ( $row = mysql_fetch_assoc($result) )
					{
					    $doc_id[] = $row['id'];

					    if ( !$executor[$e_id] && !empty($row['executive_name']) )
					    {
						$executor[$e_id] = $row['executive_name'];
						$_POST['message'] = str_replace('%ОТПРАВИТЕЛЬ%',$executor[$e_id],$_POST['message']);
					    }

					    if ( empty($body[$e_id]) )
					    {
						$body[$e_id] = $_POST['message'];
						$message->setBody($_POST['message'],$_POST['html']?'text/html':'text/plain');
					    }

					    if ( preg_match('/%(.+)%/',$body[$e_id]) || $failed[$e_id] )
					    {
						$failed[$e_id] = TRUE;
						continue;
					    }

					    $message->setFrom(array(($row['email_from_address']?$row['email_from_address']:$row['email_login'])=>$row['executive_name']));

					    if ( is_file(sprintf('%s/%s',Path_files,$row['account'])) )
						$message->attach( Swift_Attachment::fromPath(sprintf('%s/%s',Path_files,$row['account'])) );

					    if ( is_file(sprintf('%s/%s',Path_files,$row['act'])) )
					    $message->attach( Swift_Attachment::fromPath(sprintf('%s/%s',Path_files,$row['act'])) );

					    if ( is_file(sprintf('%s/%s',Path_files,$row['invoice'])) )
					    $message->attach( Swift_Attachment::fromPath(sprintf('%s/%s',Path_files,$row['invoice'])) );

					    if ( $_POST['detail'] == 'true' && !empty($row['detail']) && is_file(sprintf('%s/%s',Path_files,$row['detail'])) )
						$message->attach( Swift_Attachment::fromPath(sprintf('%s/%s',Path_files,$row['detail'])) );
					}

					if ( count($doc_id)>0 )
					{
					    $db->_doQuery(sprintf('INSERT INTO `mail_queue` (`customer_id`,`executive_id`,`status`,`message`) VALUES (%d,%d,0,\'%s\')',$rcpt['customer_id'],$e_id,base64_encode(gzcompress(serialize($message)))));
					    $k++;
					}
				    }
				}

				if ( !$failed[$e_id] ) $db->_doQuery('COMMIT');
			    }

			    if ( is_array($doc_id) && count($doc_id)>0 )
				$db->_doQuery(sprintf('UPDATE `invoice` SET `sent`=1 WHERE `id` IN(%s)',implode(',',$doc_id)));
			    else
				echo 'Похоже, документов не обработано!<br/>';

			    if ( is_array($failed) && count(array_keys($failed))>0 ) printf('Ошибочных (не отправлено): %d<br/>',count(array_keys($failed)));

			    break;

			case	'cust': // Если произвольное сообщение
			    if ( is_numeric($_POST['executive_id']) )
			    {
				if ( $executive = mysql_fetch_assoc($db->_doQuery(sprintf('SELECT * FROM `executive` WHERE id=%d AND `email_smtp` IS NOT NULL AND (`email_from_address` IS NOT NULL OR `email_login` IS NOT NULL)',$_POST['executive_id']))) )
				{ TRUE; }
				else
				{
				    die('Не выбран отправитель (исполнитель), либо для него не заданы параметры отправки!');
				}
			    }
			    else
			    {
				die('Не выбран отправитель');
			    }

			    foreach ( $_POST['recipient'] as $rcpt )
			    {
				$message= Swift_Message::newInstance();
				$rcpt	= unserialize(base64_decode($rcpt));

// Осуществляем замену ключевых слов //
				$cQuery = sprintf // Запрос на выборку всех контактов по клиенту
				(
				    'SELECT '
					.'`cs`.`email`,'
					.'`cs`.`password`,'
					.'`cn`.`contact_name`,'
					.'UCASE(`cn`.`post`) as `post`'
				    .' FROM `contact` cn'
				    .' JOIN `customer` cs ON `cs`.`account_id`=`cn`.`account_id`'
				    .' WHERE `cs`.`id`=%d'
					.' AND `cn`.`post`!=\'\''
					.' AND `cn`.`post` IS NOT NULL'
					.' AND `cn`.`contact_name`!=\'\''
					.' AND `cn`.`contact_name` IS NOT NULL',
				    $rcpt['customer_id']
				);

// %КИЛЕНТ% будет заменено на название организации
				$_POST['message'] = str_replace('%ЛИЧНЫЙ_КАБИНЕТ%',constant('UserCabinet_URL'),$_POST['message']);
				$_POST['message'] = str_replace('%КЛИЕНТ%',$rcpt['customer_name'],$_POST['message']);
				$_POST['message'] = str_replace('%ОТПРАВИТЕЛЬ%',$executive['executive_name'],$_POST['message']);

				if ( $result = $db->_doQuery($cQuery) )
				{
				    while ( $row = mysql_fetch_assoc($result) )
				    {
// Вместо %НАЗВАНИЯ ДОЛЖНОСТИ% (например, %ДИРЕКТОР%) будет подставлено имя соответствующее этой должности (из "контактов")
					$_POST['message'] = str_replace('%ЛОГИН%',$row['email'],$_POST['message']);
					$_POST['message'] = str_replace('%ПАРОЛЬ%',$row['password'],$_POST['message']);
					$_POST['message'] = str_replace(sprintf('%%%s%%',preg_replace('/\s+/','_',trim($row['post']))),$row['contact_name'],$_POST['message']);
				    }
				}

				if ( preg_match('/%(.+)%/',$_POST['message']) ) { continue; }

				$message->setFrom(array(($executive['email_from_address']?$executive['email_from_address']:$executive['email_login'])=>$executive['executive_name']));
				$message->setSubject(base64_decode($_POST['subject']));
				$message->setCharset('utf-8');

				$message->setBody($_POST['message'],$_POST['html']?'text/html':'text/plain');

				if ( !empty($_POST['debug_mail']) )
				    $message->setTo(array($_POST['debug_mail']=>$rcpt['customer_name']));

				else
				    if ( strlen($rcpt['customer_name']) <= 110 )
					$message->setTo(array($rcpt['mail']=>$rcpt['customer_name']));
				    else
					$message->setTo($rcpt['mail']);

				if ( count($_POST['file'])>0 )
				{
				    foreach ( $_POST['file'] as $att )
				    {
					$f = unserialize(base64_decode($att));
					$message->attach( Swift_Attachment::fromPath($f['path'])->setFilename($f['name']) );
				    }
				}

				$db->_doQuery(sprintf('INSERT INTO `mail_queue` (`customer_id`,`executive_id`,`status`,`message`) VALUES (%d,%d,0,\'%s\')',$rcpt['customer_id'],$_POST['executive_id'],base64_encode(gzcompress(serialize($message)))));
				$k++;
			    }
			    break;
		    }

		    printf('OK. Добавлено в очередь писем: %d',$k);
		    exit();
		}
	    }

	    $smarty->assign('f_limit',$f_limit);
	    $smarty->display('admin/mail.html');
	    break;

/*
    Блок работы с тарифами
*/
	case	'voip':
	    $smarty->display('admin/voip.html');
	    break;

	case	'session':
	    switch ($_GET['mode'])
	    {
		case	'tabsOptions':
		    if( !empty($_GET['tabId']) )
		    {
			if ( is_numeric($_GET['index']) ) { $_SESSION['options']['tabs'][$_GET['tabId']] = $_GET['index']; }
			else { unset($_SESSION['options']['tabs'][$_GET['tabId']]); }
		    }
		    break;
	    }
	    exit();
	    break;

/*
    Блок работы со справочниками
*/
	case	'dict':
	    if ( !$_SESSION['manager']['is_admin'] ) { die('Доступ запрещён'); }

	    $jqGrid = new jqGrid($_GET['name']);
	    $jqGrid->setLimit($_GET['rows']);
	    $jqGrid->setPage($_GET['page']);
	    $jqGrid->setOrder($_GET['sidx'],$_GET['sord']);

	    switch($_GET['name'])
	    {
		case	'phone_rate':
		    switch($_GET['mode'])
		    {
			case	'edit':
			    if ( !empty($_POST['rate_name']) )
			    {
				if ( is_numeric($_POST['id']) )
				{
				    $jqGrid->update($_POST['id'],array('rate_name'=>$_POST['rate_name']));
				}
				else
				{
				    //создание нового тарифа
				    $rate = new PhoneRate;
				    $rate->add($_POST['rate_name'],32);
//				    $jqGrid->insert(array('`rate_name`'=>'\''.$_POST['rate_name'].'\''));
				}
			    }
				exit();
			    break;
		    }

		    if ( $_GET['init']=='yes' )
		    {
			print json_encode
			(
			    array
			    (
				'url'		=> 'dict.php?name=phone_rate&data=yes',
				'datatype'	=> 'json',
				'pager'		=> 'rate-data-grid-pager',
				'colNames'	=> array('ID','Название тарифа'),
				'colModel'	=> array
				(
				    array('name'=>'id','width'=>50),
				    array('name'=>'rate_name','editable'=>true)
				),
				'editurl'	=> 'dict.php?mode=new&name=phone_rate',
			    )
			);
			exit();
		    }
		    elseif ( $_GET['data']=='yes' )
		    {
			$jqGrid->fields(array('id','rate_name'));
			print json_encode($jqGrid->jqGridArray());
			exit();
		    }
		    break;

		case	'rate_zone':
		    switch($_GET['mode'])
		    {
			case	'edit':
			    if ( is_numeric($_POST['id']) )
			    {
				if ( is_numeric($_GET['phone_rate_id']) )
				{
				    if ( is_numeric($_POST['cost']) )
				    {
					$jqGrid->_doQuery
					(
					    sprintf
					    (
						'UPDATE `%s` SET `cost`=%0.2f'
						    .' WHERE `zone_number`=%d'
							.' AND `phone_rate_id`=%d',
						$jqGrid->_table,
						$_POST['cost'],
						$_POST['id'],
						$_GET['phone_rate_id']
					    )
					);
				    }
				    elseif ( is_numeric($_POST['zone_number']) )
				    {
					$jqGrid->_doQuery
					(
					    sprintf
					    (
						'UPDATE `%s` SET `zone_number`=%d'
						    .' WHERE `phone_direction_id`=%d'
							.' AND `phone_rate_id`=%d',
						$jqGrid->_table,
						$_POST['zone_number'],
						$_POST['id'],
						$_GET['phone_rate_id']
					    )
					);
				    }
				}
			    }
			    elseif ( is_array($_GET['item']) )
			    {
				if ( is_numeric($_GET['new_zone']) )
				{
				    $jqGrid->_doQuery
				    (
					sprintf
					(
					    'UPDATE `%s` SET `zone_number`=%d'
					    .' WHERE `id` IN(%s)',
					    $jqGrid->_table,
					    $_GET['new_zone'],
					    implode(',',$_GET['item'])
					)
				    );
				}
			    }
			    else
			    {
			    }
			    exit();
			    break;

			case	'list':
			    if ( is_numeric($_GET['rate_id']) )
			    {
				if ( is_numeric($_GET['zone_number']) )
				{
				    if ( $_GET['_search'] == 'true' )
				    {
					switch($_GET['searchOper'])
					{
					    case	'eq':
						$filter[] = array($_GET['searchField'],'=',$_GET['searchString']);
						break;

					    case	'cn':
						$filter[] = array($_GET['searchField'],'LIKE','%'.$_GET['searchString'].'%');
						break;

					    case	'bw':
						$filter[] = array($_GET['searchField'],'LIKE',$_GET['searchString'].'%');
						break;
					}

//					exit();
				    }

				    if ( $search = $jqGrid->_where($filter,'AND',true) )
				    {
					$search = ' AND '.$search;
				    }

				    $jqGrid->_query		= sprintf('SELECT `rate_zone`.`id` AS `id`,`prefix`,`title` FROM `phone_direction` JOIN `rate_zone` ON `phone_direction`.`id`=`rate_zone`.`phone_direction_id` WHERE `zone_number`=%d AND `phone_rate_id`=%d %s %s %s',$_GET['zone_number'],$_GET['rate_id'],$search,$jqGrid->_order(),$jqGrid->_limit());
				    $jqGrid->_count_query	= sprintf('SELECT `phone_direction`.`id` FROM `phone_direction` JOIN `rate_zone` ON `phone_direction`.`id`=`rate_zone`.`phone_direction_id` WHERE `zone_number`=%d AND `phone_rate_id`=%d %s',$_GET['zone_number'],$_GET['rate_id'],$search);
				}
				else
				{
				    $jqGrid->_query		= sprintf('SELECT `phone_rate_id`,`zone_number` AS `id`,`cost` FROM `rate_zone` WHERE `phone_rate_id`=%d GROUP BY `zone_number` %s %s',$_GET['rate_id'],$jqGrid->_order(),$jqGrid->_limit());
				    $jqGrid->_count_query	= sprintf('SELECT DISTINCT `zone_number` FROM `rate_zone` WHERE `phone_rate_id`=%d',$_GET['rate_id']);
				}
				print json_encode($jqGrid->jqGridArray());
//				exit;
			    }
			    exit();
			    break;
		    }
		    break;

		case	'phone_direction':
		    if ( $_GET['init']=='yes' )
		    {
			print json_encode
			(
			    array
			    (
				'url'		=> 'dict.php?name=phone_direction&data=yes',
				'datatype'	=> 'json',
				'pager'		=> 'data-grid-pager',
				'colNames'	=> array('ID','Префикс','Направление'),
				'rowNum'	=> 100,
				'colModel'	=> array
				(
				    array('name'=>'id','width'=>50),
				    array('name'=>'prefix'),
				    array('name'=>'title','editable'=>true,'width'=>300),
				),
				'sortname'	=> 'title',
				'sortorder'	=> 'asc',
//				'grouping'	=> true,
//				'groupingView'	=> array
//				(
//				    'groupField'	=> array('title'),
//				    'groupCollapse'	=> true
//				)
			    )
			);
			exit();
		    }
		    elseif ( !empty($_GET['term']) )
		    {
			print json_encode($jqGrid->like(array('title',$_GET['term'])));
			exit();
		    }
		    elseif ( $_GET['mode']=='list' )
		    {
			if ( $_GET['_search'] == 'true' )
			{
			    switch($_GET['searchOper'])
			    {
				case	'eq':
				    $filter[] = array($_GET['searchField'],'=',$_GET['searchString']);
				    break;

				case	'cn':
				    $filter[] = array($_GET['searchField'],'LIKE','%'.$_GET['searchString'].'%');
				    break;

				case	'bw':
				    $filter[] = array($_GET['searchField'],'LIKE',$_GET['searchString'].'%');
				    break;
			    }
			}

			if ( is_numeric($_GET['phone_rate_id']) )
			{
			    $filter[] = array('`phone_rate_id`',$_GET['phone_rate_id']);

			    if ( is_numeric($_GET['id']) )
			    {
				$filter[] = array('`zone_number`',$_GET['id']);

				$jqGrid->_query		= sprintf('SELECT `rate_zone`.`id`,`prefix`,`title` FROM `phone_direction` JOIN `rate_zone` ON `rate_zone`.`phone_direction_id`=`phone_direction`.`id` %s %s %s',$jqGrid->_where($filter,'AND',false),$jqGrid->_order(),$jqGrid->_limit());
//				$jqGrid->_count_query	= sprintf('SELECT DISTINCT `zone_number` FROM `rate_zone` WHERE ';
			    }
			    else
			    {
				$jqGrid->_query		= sprintf('SELECT `phone_direction`.`id`,`prefix`,`title`,`zone_number` FROM `phone_direction` JOIN `rate_zone` ON `rate_zone`.`phone_direction_id`=`phone_direction`.`id` %s %s %s',$jqGrid->_where($filter,'AND',false),$jqGrid->_order(),$jqGrid->_limit());
				$jqGrid->_count_query	= sprintf('SELECT `phone_direction`.`id` FROM `phone_direction` JOIN `rate_zone` ON `rate_zone`.`phone_direction_id`=`phone_direction`.`id` %s',$jqGrid->_where($filter,'AND',false));
			    }
			    print json_encode($jqGrid->jqGridArray());
			}
			else
			{
			    $jqGrid->_query		= sprintf('SELECT `phone_direction`.`id`,`prefix`,`title`,`zone_number` FROM `phone_direction` JOIN `rate_zone` ON `rate_zone`.`phone_direction_id`=`phone_direction`.`id` %s %s %s',$jqGrid->_where($filter,'AND',false),$jqGrid->_order(),$jqGrid->_limit());
//			    $jqGrid->_count_query	= sprintf('SELECT `phone_direction`.`id` FROM `phone_direction` JOIN `rate_zone` ON `rate_zone`.`phone_direction_id`=`phone_direction`.`id` %s',$jqGrid->_where($filter,'AND',false));
//			    error_log($jqGrid->_query);
			    print json_encode($jqGrid->jqGridArray());
			}
			exit();
		    }
		    break;

		default:
		    exit();
	    }

	    $smarty->display('admin/dictionary2.html');
	    break;

	case	'timeReport':
	    $arTime = new ArrivalTime;

	    if ( $_GET['do'] == 'init' )
	    {
		print json_encode($arTime->jqGridOptions);
		exit();
	    }
	    elseif ( is_numeric($_REQUEST['id']) )
	    {
		mysql_query(sprintf('UPDATE `arrival_time` SET `cost_fine`=\'%0.2f\' WHERE `id`=%d',$_REQUEST['cost'],$_REQUEST['id'])) or error_log(mysql_error());
		exit();
	    }
	    elseif ( $_REQUEST['get_summary'] == 'yes' )
	    {
		$filter = NULL;

		if ( is_numeric($_GET['manager_id']) )
		{
		    $filter .= sprintf(' AND `manager_id` = %d',$_REQUEST['manager_id']);
		}

		if ( $result = mysql_query(sprintf('SELECT SUM(`cost_fine`) FROM `arrival_time` WHERE `date_time` BETWEEN \'%s\' AND \'%s\' %s',$_REQUEST['startDate'],$_REQUEST['stopDate'])) )
		    if ( $row = mysql_fetch_row($result) )
			exit(json_encode(array('userdata'=>array('cost'=>$row[0]))));
	    }
	    else
	    {
		if ( is_numeric($_GET['manager_id']) )
		{
		    $arTime->_filter[] = array('`manager_id`',$_GET['manager_id']);
		}

		$arTime->setPage($_GET['page']);
		$arTime->setLimit($_GET['rows']);
		$arTime->setOrder($_GET['sidx'],$_GET['sord']);

		print json_encode($arTime->timeReport($_GET['startDate'],$_GET['stopDate']));
	    }
	    break;

/*
    Блок детализации звонков
*/
	case	'detail':
	    if ( count($_GET['service_id'])==0 ) { die(json_encode(array())); }

// Подсчёт общего количества записей
	    $query = sprintf
	    (
		'SELECT COUNT(*)'
		.' FROM detalisation det'
		.' JOIN service_phone_number spn ON det.service_phone_number_id = spn.id'
		.' JOIN service ser ON ser.id = spn.service_id'
		.' WHERE ser.id IN(%s)'
		    .' AND date BETWEEN %s AND %s',
		implode(',',$_GET['service_id']),
		($_GET['date_start']?sprintf('\'%s\'',$_GET['date_start']):'DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1 MONTH),\'%Y-%m-01\')'),
		($_GET['date_stop']?sprintf('\'%s\' + INTERVAL 1 DAY',$_GET['date_stop']):'LAST_DAY(DATE_SUB(NOW(), INTERVAL 1 MONTH))')
	    );

	    if ( $result = mysql_query($query) ) { $count = mysql_fetch_array($result); } else { die(mysql_error()); }

	    if ( $_GET['csv'] == 'yes' )
	    {
		header('Content-Type: text/plain; charset=utf-8'); 
		header('Content-Disposition: attachment; filename=detail.csv'); 

		foreach ( $_GET['service_id'] as $id )
		{
		    $query = sprintf
		    (
			'SELECT '
//			    .'det.id,'
			    .'spn.phone_number,'
			    .'det.dst,'
			    .'det.duration,'
			    .'CONCAT(SUBSTRING_INDEX(det.cost,\'.\',1),\',\',SUBSTRING_INDEX(det.cost,\'.\',-1)) as cost,'
			    .'det.date,'
			    .'det.cost AS `cost_float`,'
			    .'pd.title'
			.' FROM detalisation det'
			.' JOIN service_phone_number spn ON det.service_phone_number_id = spn.id'
			.' JOIN service ser ON ser.id = spn.service_id'
			.' JOIN phone_direction pd ON det.phone_direction_id = pd.id'
			.' WHERE ser.id IN(%s)'
			    .' AND date BETWEEN %s AND %s'
			.' ORDER BY `det`.`date`',
			$id,
			($_GET['date_start']?sprintf('\'%s\'',$_GET['date_start']):'DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1 MONTH),\'%Y-%m-01\')'),
			($_GET['date_stop']?sprintf('\'%s\' + INTERVAL 1 DAY',$_GET['date_stop']):'LAST_DAY(DATE_SUB(NOW(), INTERVAL 1 MONTH))')
		    );

		    if ( $result = mysql_query($query) )
		    {
			$total = array();

			while ( $row = mysql_fetch_row($result) )
			{
			    //$row[2] = ($row[2]%60)>5 ? ceil($row[2]/60) : floor($row[2]/60); // Округление до минут
			    $row[2] = ceil($row[2]/60); // Округление до минут
			    

			    $total['number']	= $row[0];
			    $total['duration']	+= $row[2];
			    $total['sum']	+= $row[5];
			    $total['count']++;

			    unset($row[5]);

			    if ( $_GET['in_win'] == 'yes' )
			    {
				printf("%s\n",iconv('utf-8','windows-1251',implode(';',$row)));
			    }
			    else
			    {
				printf("%s\n",implode(';',$row));
			    }
			}

			echo ";;\n";

			if ( $_GET['in_win'] == 'yes' )
			{
			    printf
			    (
				"%s\n",
				iconv
				(
				    'utf-8',
				    'windows-1251',
				    implode
				    (
					' ',
					array
					(
					    sprintf('ИТОГО ПО НОМЕРУ %s',$total['number']),
					    sprintf('ВЫЗОВОВ %d',$total['count']),
					    sprintf('ПРОДОЛЖИТЕЛЬНОСТЬ %d ч. %d мин.',ceil($total['duration']/60),$total['duration']%60),
					    sprintf('НА СУММУ %0.2f',$total['sum']),
					    NULL,
					    NULL
					)
				    )
				)
			    );
			}
			else
			{
			    printf
			    (
				"%s\n",
				implode
				(
				    ' ',
				    array
				    (
					sprintf('ИТОГО ПО НОМЕРУ %s',$total['number']),
					sprintf('ВЫЗОВОВ %d',$total['count']),
					sprintf('ПРОДОЛЖИТЕЛЬНОСТЬ %d ч. %d мин.',ceil($total['duration']/60),$total['duration']%60),
					sprintf('НА СУММУ %0.2f',$total['sum']),
					NULL,
					NULL
				    )
				)
			    );
			}

			echo "########################################################################;\n";
		    }
		}

		exit();
	    }

	    $query = sprintf
	    (
		'SELECT '
		    .'det.id,'
		    .'spn.phone_number,'
		    .'det.dst,'
		    .'det.duration,'
		    .'CONCAT(SUBSTRING_INDEX(det.cost,\'.\',1),\',\',SUBSTRING_INDEX(det.cost,\'.\',-1)) as cost,'
		    .'det.date,'
		    .'pd.title'
		.' FROM detalisation det'
		.' JOIN service_phone_number spn ON det.service_phone_number_id = spn.id'
		.' JOIN service ser ON ser.id = spn.service_id'
		.' JOIN phone_direction pd ON det.phone_direction_id = pd.id'
		.' WHERE ser.id IN(%s)'
		    .' AND date BETWEEN %s AND %s'
		.' ORDER BY `det`.`date`'
		.' LIMIT %d,%d',
		implode(',',$_GET['service_id']),
		($_GET['date_start']?sprintf('\'%s\'',$_GET['date_start']):'DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1 MONTH),\'%Y-%m-01\')'),
		($_GET['date_stop']?sprintf('\'%s\' + INTERVAL 1 DAY',$_GET['date_stop']):'LAST_DAY(DATE_SUB(NOW(), INTERVAL 1 MONTH))'),
		$_GET['rows']*($_GET['page']-1),
		$_GET['rows']
	    );

	    if ( $result=mysql_query($query) )
	    {
		while ( $row = mysql_fetch_assoc($result) )
		{
		    //$row['duration'] = ($row['duration']%60)>5 ? ceil($row['duration']/60) : floor($row['duration']/60); // Округление до минут
		    $row['duration'] = ceil($row['duration']/60); // Округление до минут

		    $data[] = array('id'=>$row['id'],'cell'=>array_values($row));
		}

//		die($query);

		echo json_encode
		(
		    array
		    (
			'records'	=> $count[0],
			'total'	=> ceil($count[0]/$_GET['rows']),
			'page'	=> $_GET['page'],
			'rows'	=> $data
		    )
		);
	    } else { die($query); }
	    exit();
	    break;

	case	'options':
	    if ( !empty($_GET['module']) )
	    {
		foreach ( $_GET as $key => $value )
		{
		    if ( $key == 'module' || $key == 'moduleName' || $key == 'action' ) { continue; }
		    $_SESSION['manager']['options'][$_GET['module']][$_GET['moduleName']][$key] = $value;
		}

		mysql_query(sprintf('UPDATE `manager` SET `options`=\'%s\' WHERE `id`=%d',mysql_escape_string(json_encode($_SESSION['manager']['options'])),$_SESSION['manager']['id']));
	    }
	    else
	    {
		print json_encode($_SESSION['manager']['options']);
	    }
	    break;

	case	'task':
	    $task = new webTask;

	    if ( is_numeric($_GET['id']) )
	    {
		$task->getById($_GET['id'])->show();
	    }
	    else
	    {
		unset($_SESSION['filter']['task']);

		$_SESSION['filter']['task'] = array
		(
		    'display'	=> 'opened',
		    'rm_id'	=> $_SESSION['manager']['id']
		);

		if ( $_GET['do'] == 'filter' )
		{
		    unset($_SESSION['filter']['task']);

		    foreach ( $_GET as $key => $value )
		    {
			if ( $key == 'action' || $key == 'do' ) { continue; }
			if ( !empty($value) ) { $_SESSION['filter']['task'][$key] = $value; }
		    }
		}

		if ( empty($_SESSION['manager']['is_admin']) ) { $_SESSION['filter']['task']['rm_id'] = $_SESSION['manager']['id']; }

		$task->addFilter($_SESSION['filter']['task']);
		$task->getList()->show();
	    }
	    break;

// Проверка телефонного номера
	case	'check.number':
	    $data = array();

	    if ( !empty($_GET['num']) )
	    {
		if ( $num = mysql_fetch_row(mysql_query(sprintf('SELECT `id` FROM `service_phone_number` WHERE `phone_number`=\'%s\'',$_GET['num']))) )
		{
		    if ( $num[0]>0 ) { $data['r'] = 'BUSY'; }
		}
	    }

	    echo json_encode($data);
	    exit();
	    break;

// Создание счета
	case	'invoice.create':
	    $data = array();

	    if ( is_numeric($_GET['account_id']) && !empty($_GET['date']) && count($_GET['service_id'])>0 )
	    {
		$i = 0;

		mysql_query('START TRANSACTION');
		mysql_query(sprintf('INSERT INTO `invoice_create_queue` (`account_id`,`from_data`,`create_date`) VALUES (%d,\'%s\',NOW())',$_GET['account_id'],$_GET['date']));

		$qid = mysql_insert_id();
		if ( is_numeric($qid) )
		{
		    foreach ( $_GET['service_id'] as $service_id )
		    {
			$i++;
			mysql_query(sprintf('INSERT INTO `optional_services` (`invoice_create_queue_id`,`service_id`) VALUES (%d,%d)',$qid,$service_id));
		    }
		}

		mysql_query('COMMIT');

		$data['r'] = 'OK';
		$data['count'] = $i;
	    }

	    echo json_encode($data);
	    exit();
	    break;

// Запрос данных для чарта
	case	'chart.status':
	    $data = array();

	    if ( $result = mysql_query('SELECT `s`.`status_name`,COUNT(*) AS `qty` FROM `customer` c LEFT JOIN `status` s on `s`.`id`=`c`.`status_id` GROUP BY `s`.`id` ORDER BY `qty` DESC') )
	    {
		while ( $row = mysql_fetch_row($result) )
		{
		    $data[] = $row;
		}
	    }

	    echo json_encode($data);
	    exit();
	    break;

// Удаление счетов
	case	'invoice.delete':
	    if ( is_numeric($_GET['id']) )
	    {
		if ( $invoice = mysql_fetch_assoc(mysql_query(sprintf('SELECT `i`.*,`c`.`account_id`,`c`.`executive_id` FROM `invoice` i JOIN `contract` c ON `c`.`id`=`i`.`contract_id` WHERE `i`.`id`=%d',$_GET['id']))) )
		{
//		    mysql_query('START TRANSACTION');
//		    mysql_query(sprintf('DELETE FROM `invoice_items` WHERE `invoice_id`=%d',$invoice['id'])); // Удаляем имеющиеся записи по счету
			mysql_query(sprintf('UPDATE service SET last_inv_date=last_inv_date - INTERVAL 1 MONTH WHERE id IN (%s) AND completed IS NULL',$invoice['service_id_list']));
			mysql_query(sprintf('UPDATE service SET completed=NULL, last_inv_date=last_inv_date - INTERVAL 1 MONTH WHERE id IN (%s) AND completed=1',$invoice['service_id_list']));
		    mysql_query(sprintf('DELETE FROM `invoice` WHERE `id`=%d',$invoice['id'])); // Удаляем счет
//		    mysql_query('COMMIT');

		    if ( $err = mysql_error() ) { die($query.': '.$err); }

// Удаляем существующие документы
		    if ( !empty($invoice['account']) )
		    {
			$path = sprintf('%s/%s',Path_files,$invoice['account']);
			if ( file_exists($path) ) { unlink($path); }
		    }

		    if ( !empty($invoice['act']) )
		    {
			$path = sprintf('%s/%s',Path_files,$invoice['act']);
			if ( file_exists($path) ) { unlink($path); }
		    }

		    if ( !empty($invoice['invoice']) )
		    {
			$path = sprintf('%s/%s',Path_files,$invoice['invoice']);
			if ( file_exists($path) ) { unlink($path); }
		    }

		    if ( !empty($invoice['detail']) )
		    {
			$path = sprintf('%s/%s',Path_files,$invoice['detail']);
			if ( file_exists($path) ) { unlink($path); }
		    }
		}
	    }
	    header(sprintf('Location: %s',$_SERVER['HTTP_REFERER']));
	    exit();
	    break;

// Перевыставление счетов
	case	'invoice.remake':


	    if ( is_numeric($_GET['id']) )
	    {
		if ( $invoice = mysql_fetch_assoc(mysql_query(sprintf('SELECT `i`.*,`c`.`account_id`,`c`.`executive_id` FROM `invoice` i JOIN `contract` c ON `c`.`id`=`i`.`contract_id` WHERE `i`.`id`=%d',$_GET['id']))) )
		{
		    mysql_query('START TRANSACTION');
		    mysql_query(sprintf('DELETE FROM `invoice_items` WHERE `invoice_id`=%d',$invoice['id'])); // Удаляем имеющиеся записи по счету
		    mysql_query // Создаем новое задание в очереди
		    (
			sprintf
			(
			    'INSERT INTO `invoice_create_queue` (`account_id`,`create_date`,`invoice_id`,`from_data`)'
			    .' VALUES (%d,NOW(),%d,\'%s\')',
			    $invoice['account_id'],
			    $invoice['id'],
			    $invoice['date']
			)
		    );

		    $qid = mysql_insert_id(); // Получаем ID задания

		    if ( is_numeric($qid) )
		    {
// Удаляем существующие документы
			if ( !empty($invoice['account']) )
			{
			    $path = sprintf('%s/%s',Path_files,$invoice['account']);
			    if ( file_exists($path) ) { unlink($path); }
			    mysql_query(sprintf('UPDATE `invoice` SET `account`=NULL WHERE `id`=%d',$invoice['id']));
			}

			if ( !empty($invoice['act']) )
			{
			    $path = sprintf('%s/%s',Path_files,$invoice['act']);
			    if ( file_exists($path) ) { unlink($path); }
			    mysql_query(sprintf('UPDATE `invoice` SET `act`=NULL WHERE `id`=%d',$invoice['id']));
			}

			if ( !empty($invoice['invoice']) )
			{
			    $path = sprintf('%s/%s',Path_files,$invoice['invoice']);
			    if ( file_exists($path) ) { unlink($path); }
			    mysql_query(sprintf('UPDATE `invoice` SET `invoice`=NULL WHERE `id`=%d',$invoice['id']));
			}

			if ( !empty($invoice['detail']) )
			{
			    $path = sprintf('%s/%s',Path_files,$invoice['detail']);
			    if ( file_exists($path) ) { unlink($path); }
			    mysql_query(sprintf('UPDATE `invoice` SET `detail`=NULL WHERE `id`=%d',$invoice['id']));
			}

// Запрашиваем список услуг для абонента по исполнителю
			if ( $result = mysql_query(sprintf('SELECT `id` FROM `service` WHERE `account_id`=%d AND `executive_id`=%d',$invoice['account_id'],$invoice['executive_id'])) )
			{
			    while ( $row = mysql_fetch_row($result) )
			    {
// Добавляем каждую услугу в очередь на формирование счета
				//mysql_query(sprintf('UPDATE `service` SET `completed`=NULL WHERE `id`=%d',$row[0]));
			    mysql_query(sprintf('UPDATE service SET completed=NULL, last_inv_date=last_inv_date - INTERVAL 1 MONTH WHERE stop_date = last_inv_date AND id=%d AND completed=1',$row[0]));
			    mysql_query(sprintf('UPDATE service SET last_inv_date=last_inv_date - INTERVAL 1 MONTH WHERE id=%d AND completed IS NULL',$row[0]));
				mysql_query(sprintf('INSERT INTO `optional_services` (`invoice_create_queue_id`,`service_id`) VALUES(%d,%d)',$qid,$row[0]));
			    }

			    mysql_query(sprintf('UPDATE `invoice` SET `status`=0 WHERE `id`=%d',$invoice['id']));
			}

			mysql_query('COMMIT');
		    }
		}
	    }
	    else
	    if ( is_array($_SESSION['select']['customer']) && count($_SESSION['select']['customer'])>0 )
	    {
		if ( $result = mysql_query(sprintf('SELECT `i`.`id` FROM `invoice` i JOIN `contract` ct ON `ct`.`id`=`i`.`contract_id` JOIN `customer` cs ON `cs`.`account_id`=`ct`.`account_id` WHERE `i`.`date`=\'%s\' AND `cs`.`id` IN (%s)',$_GET['make_date'],implode(',',array_keys($_SESSION['select']['customer'])))) )
		{
		    while ( $row = mysql_fetch_row($result) )
		    {
/* Копия предыдущей функции перевыставления единичного счета, завернутая в цикл */
		if ( $invoice = mysql_fetch_assoc(mysql_query(sprintf('SELECT `i`.*,`c`.`account_id`,`c`.`executive_id` FROM `invoice` i JOIN `contract` c ON `c`.`id`=`i`.`contract_id` WHERE `i`.`id`=%d',$row[0]))) )
		{
		    mysql_query('START TRANSACTION');
		    mysql_query(sprintf('DELETE FROM `invoice_items` WHERE `invoice_id`=%d',$invoice['id'])); // Удаляем имеющиеся записи по счету
		    mysql_query // Создаем новое задание в очереди
		    (
			sprintf
			(
			    'INSERT INTO `invoice_create_queue` (`account_id`,`create_date`,`invoice_id`,`from_data`)'
			    .' VALUES (%d,NOW(),%d,\'%s\')',
			    $invoice['account_id'],
			    $invoice['id'],
			    $invoice['date']
			)
		    );

		    $qid = mysql_insert_id(); // Получаем ID задания

		    if ( is_numeric($qid) )
		    {
// Удаляем существующие документы
			if ( !empty($invoice['account']) )
			{
			    $path = sprintf('%s/%s',Path_files,$invoice['account']);
			    if ( file_exists($path) ) { unlink($path); }
			    mysql_query(sprintf('UPDATE `invoice` SET `account`=NULL WHERE `id`=%d',$invoice['id']));
			}

			if ( !empty($invoice['act']) )
			{
			    $path = sprintf('%s/%s',Path_files,$invoice['act']);
			    if ( file_exists($path) ) { unlink($path); }
			    mysql_query(sprintf('UPDATE `invoice` SET `act`=NULL WHERE `id`=%d',$invoice['id']));
			}

			if ( !empty($invoice['invoice']) )
			{
			    $path = sprintf('%s/%s',Path_files,$invoice['invoice']);
			    if ( file_exists($path) ) { unlink($path); }
			    mysql_query(sprintf('UPDATE `invoice` SET `invoice`=NULL WHERE `id`=%d',$invoice['id']));
			}

			if ( !empty($invoice['detail']) )
			{
			    $path = sprintf('%s/%s',Path_files,$invoice['detail']);
			    if ( file_exists($path) ) { unlink($path); }
			    mysql_query(sprintf('UPDATE `invoice` SET `detail`=NULL WHERE `id`=%d',$invoice['id']));
			}

// Запрашиваем список услуг для абонента по исполнителю
			if ( $result = mysql_query(sprintf('SELECT `id` FROM `service` WHERE `account_id`=%d AND `executive_id`=%d',$invoice['account_id'],$invoice['executive_id'])) )
			{
			    while ( $row = mysql_fetch_row($result) )
			    {
// Добавляем каждую услугу в очередь на формирование счета
				mysql_query(sprintf('UPDATE `service` SET `completed`=NULL WHERE `id`=%d',$row[0]));
				mysql_query(sprintf('INSERT INTO `optional_services` (`invoice_create_queue_id`,`service_id`) VALUES(%d,%d)',$qid,$row[0]));
			    }

			    mysql_query(sprintf('UPDATE `invoice` SET `status`=0 WHERE `id`=%d',$invoice['id']));
			}

			mysql_query('COMMIT');
		    }
		}

////////////////////////////////////////////////////////////////////
		    }
		}
	    }
	    header(sprintf('Location: %s',$_SERVER['HTTP_REFERER']));
	    exit();
	    break;

	case	'verification':
	    $data = array();

	    switch ( $_GET['do'] )
	    {
		case	'add':
		    if ( is_numeric($_GET['contract_id']) )
		    {
			if ( mysql_query(sprintf('INSERT INTO `verification_act` (`contract_id`,`period_start`,`period_stop`,`status`) VALUES (%d,\'%s\',\'%s\',0)',$_GET['contract_id'],$_GET['period_start'],$_GET['period_stop'])) )
			{
			    $data['code'] = 200;
			}
			else
			{
			    error_log(mysql_error());
			}
		    }
		    break;

		case	'get':
		    if ( is_numeric($_GET['id']) )
		    {
			$data = mysql_fetch_assoc(mysql_query(sprintf('SELECT * FROM `verification_act` WHERE `id`=%d',$_GET['id'])));
		    }
		    break;

		case	'delete':
		    if ( is_numeric($_GET['id']) && $_GET['id']>0 )
		    {
			if ( mysql_query(sprintf('DELETE FROM `verification_act` WHERE `id`=%d',$_GET['id'])) ) { $data['code'] = 200; }
		    }
		    break;

		default:
		    if ( is_numeric($_GET['contract_id']) )
		    {
			$count = mysql_fetch_row(mysql_query(sprintf('SELECT COUNT(*) FROM `verification_act` WHERE `contract_id`=%d',$_GET['contract_id'])));

			$data['records'] = $count[0];
			$data['total'] = ceil($data['records']/$_GET['rows']);
			$data['page'] = $_GET['page'];

			if ( $result = mysql_query(sprintf('SELECT `va`.`id`,`va`.`period_start`,`va`.`period_stop`,`va`.`turnover_credit`,`va`.`turnover_debet`,(`va`.`turnover_credit`-`va`.`turnover_debet`) AS `saldo` FROM `verification_act` va WHERE `contract_id`=%d ORDER BY `%s` %s LIMIT %d,%d',$_GET['contract_id'],$_GET['sidx'],strtoupper($_GET['sord']),($_GET['rows']*($_GET['page']-1)),$_GET['rows'])) )
			{
			    while ( $row = mysql_fetch_assoc($result) )
			    {
				$data['rows'][] = array('id'=>$row['id'],'cell'=>array_values($row));
			    }
			}
		    }
		    break;
	    }

	    echo json_encode($data);
	    exit();
	    break;

	case	'payment':
	    $data = array();

	    switch ( $_GET['do'] )
	    {
		case	'add':
		    if ( is_numeric($_GET['contract_id']) )
		    {
			if ( mysql_query(sprintf('INSERT INTO `payment` (`contract_id`,`date`,`sum`,`comment`) VALUES (%d,\'%s\',\'%0.2f\',\'%s\')',$_GET['contract_id'],$_GET['date'],$_GET['sum'],mysql_escape_string($_GET['comment']))) )
			{
			    $data['code'] = 200;
			}
			else
			{
			    error_log(mysql_error());
			}
		    }
		    break;

		case	'edit':
		    if ( is_numeric($_POST['id']) )
		    {
			mysql_query(sprintf('UPDATE `payment` SET `date`=\'%s\',`sum`=%0.2f,comment=\'%s\' WHERE `id`=%d',$_POST['date'],$_POST['sum'],mysql_escape_string($_POST['comment']),$_POST['id']));
		    }
		    break;

		case	'delete':
		    if ( is_numeric($_GET['id']) )
		    {
			mysql_query(sprintf('DELETE FROM `payment` WHERE `id`=%d',$_GET['id']));
			$data['code'] = 200;
		    }
		    break;

		default:
		    if ( is_numeric($_GET['contract_id']) )
		    {
			$count = mysql_fetch_row(mysql_query(sprintf('SELECT COUNT(*) FROM `payment` WHERE `contract_id`=%d',$_GET['contract_id'])));

			$data['records'] = $count[0];
			$data['total'] = ceil($data['records']/$_GET['rows']);
			$data['page'] = $_GET['page'];

			if ( $result = mysql_query(sprintf('SELECT `p`.`id`,`p`.`date`,`p`.`sum`,`p`.`comment` FROM `payment` p WHERE `contract_id`=%d ORDER BY `%s` %s LIMIT %d,%d',$_GET['contract_id'],$_GET['sidx'],strtoupper($_GET['sord']),($_GET['rows']*($_GET['page']-1)),$_GET['rows'])) )
			{
			    while ( $row = mysql_fetch_assoc($result) )
			    {
				$data['rows'][] = array('id'=>$row['id'],'cell'=>array_values($row));
			    }
			}
		    }
		    break;
	    }

	    echo json_encode($data);
	    exit();
	    break;

	case	'service':
	case	'contact':
	case	'document':
	case	'group':
	case	'status':
	    if ( sizeof($_POST)>1 )
	    {
			$fields = array();

			foreach ( $_POST as $key => $value )
			{
		    	if ( $key == 'class' || $key == 'id' || $key == 'phone_number' || $key == 'phone_rate_id' ) { continue; }
		    	$fields[] = sprintf('`%s`=\'%s\'',mysql_escape_string($key),mysql_escape_string($value));
			}

			if ( isset($_POST['class']) )
			{
		    	switch ( $_POST['class'] )
		    	{
					case	'contact':
			    		if ( !empty($_POST['phone_number']) )
			    		{
							$fields[] = sprintf('`%s`=\'%s\'','phone_number',$_POST['phone_number']);
			    		}
			    	break;
		    	}
			}
		

			if($_POST['service_name_id']==30)
			{
				#$fp = fopen("/tmp/log2", "a+"); 
				
				
				mysql_query(sprintf('update crm.service_phone_number set phone_rate_id=%d where service_id=%d',$_POST['phone_rate_id'],$_POST['id']));

				#$_POST['fix_ip_address_enable']="NULL";
				#echo "blablabla =".$_POST['fix_ip_address_enable'];

				$voip_service_querry=sprintf('UPDATE '.
										'crm.voip_service '.
									'SET '.
										'city_uplink_id=%s, '.
										'zona_mobile_uplink_id=%s, '.
										'zona_mobile_uplink_reserve_id=%s, '.
										'zona_stationary_uplink_id=%s, '.
										'zona_stationary_uplink_reserve_id=%s, '.
										'long_distance_uplink_id=%s, '.
										'long_distance_uplink_reserve_id=%s, '.
										'international_uplink_id=%s, '.
										'international_uplink_reserve_id=%s, '.
										'number_of_channel=%d, '.
										'fix_ip_address_enable=%d, '.
										'fix_ip_address=\'%s\', '.
										'call_forward=%d, '.
										'forward_number=\'%s\', '.
										'forward_timeout=%d '.
									'WHERE '.
										'service_id=%d',
										$_POST['city_uplink_id'],
										$_POST['zona_mobile_uplink_id'],
										$_POST['zona_mobile_uplink_reserve_id'],
										$_POST['zona_stationary_uplinks_id'],
										$_POST['zona_stationary_uplinks_reserve_id'],
										$_POST['long_distance_uplinks_id'],
										$_POST['long_distance_uplinks_reserve_id'],
										$_POST['international_uplinks_id'],
										$_POST['international_uplinks_reserve_id'],
										$_POST['number_of_channels'],
										$_POST['fix_ip_address_enable'],
										$_POST['fix_ip_address'],
										$_POST['call_forward'],
										$_POST['forward_number'],
										$_POST['forward_timeout'],
										$_POST['id']);
				#print $voip_service_querry;

				mysql_query($voip_service_querry);

				$voip_service_querry2=sprintf('UPDATE '.
												'crm.service '.
												'SET '.
													'executive_id = %d, '.
													'cost=\'%s\', '.
													'monthly=%d, '.
													'start_date=\'%s\', '.
													'stop_date=\'%s\', '.
													'date_of_invoice=%d, '.
													'payment_delay=%d, '.
													'contract_id=%d '.
												'WHERE '.
													'id=%d',
													$_POST['executive_id'],
													$_POST['cost'],
													$_POST['monthly'],
													$_POST['start_date'],
													$_POST['stop_date'],
													$_POST['date_of_invoice'],
													$_POST['payment_delay'],
													$_POST['contract_id'],
													$_POST['id']);

				mysql_query($voip_service_querry2);

				


			}
			else
			{
				if ( is_numeric($_POST['phone_rate_id']) && !empty($_POST['phone_number']) )
				{
		    		mysql_query(sprintf('UPDATE `service_phone_number` SET `phone_rate_id`=%d,`phone_number`=\'%s\' WHERE `service_id`=%d',$_POST['phone_rate_id'],$_POST['phone_number'],$_POST['id']));
				}
			
				if ( $_GET['action']=='service' && empty($_POST['monthly']) )
				{
			   		$fields[] = '`monthly`=0';
				}
			
				$query = sprintf('UPDATE `%s` SET %s WHERE `id`=%d',$_GET['action'],implode(',',$fields),$_POST['id']);
				mysql_query($query)||die(sprintf("Q: '%s;'<br/>\nA: %s",$query,mysql_error()));
				if ($_GET['action']=='service') { $_GET['action'] = 'services'; }
			}
			header(sprintf('Location: %s#%s',$_SERVER['HTTP_REFERER'],$_GET['action']));
	    }
	    else if ( isset($_GET['id']) )
	    {
/*

// Исполнители
	    $result = mysql_query('SELECT * FROM `executive` ORDER BY `executive_name`');
	    while( $row = mysql_fetch_assoc($result) )
	    {
		$executive[] = $row;
	    }
	    $smarty->assign('executives',$executive);
*/

// Тарифы на телефонию
	    $result = mysql_query('SELECT * FROM `phone_rate` ORDER BY `rate_name`');
	    while( $row = mysql_fetch_assoc($result) )
	    {
		$phone_rate[] = $row;
	    }
	    $smarty->assign('phone_rates',$phone_rate);

/*
// Услуги
	    $result = mysql_query('SELECT * FROM `service_name` ORDER BY `service_name`');
	    while( $row = mysql_fetch_assoc($result) )
	    {
		$service_name[] = $row;
	    }
	    $smarty->assign('service_names',$service_name);
*/
		if ( $_GET['action']=='service' )
		{
		    $query = sprintf
		    (
			'SELECT *,`service`.`id` AS `srv_id`,`city_uplink`.`name` AS city_name,  `zona_mobile_uplink`.`name` AS `zona_mobile_name`, `zona_mobile_uplink_reserve`.`name` AS `zona_mobile_name_reserve_name`,'
				.' `zona_stationary_uplink`.name AS `zona_stationary_name`,`zona_stationary_uplink_reserve`.`name` AS `zona_stationary_uplink_reserve_name`,`long_distance_uplink`.`name` AS `long_distance_name`,`long_distance_uplink_reserve`.`name` AS `long_distance_name_reserve`, '
				.' `international_uplink`.`name` AS `international_name`,`international_uplink_reserve`.`name` AS `international_reserve_name` FROM `service`'
			    .' JOIN `service_name` ON `service_name`.`id`=`service`.`service_name_id`'
			    .' JOIN `executive` ON `executive`.`id`=`service`.`executive_id`'
			    .' LEFT JOIN `service_phone_number` ON `service`.`id`=`service_phone_number`.`service_id`'
			    .' LEFT JOIN `phone_rate` ON `phone_rate`.`id`=`service_phone_number`.`phone_rate_id`'
			    .' LEFT JOIN `voip_service` ON `voip_service`.`service_id` = `service`.`id`'
			    .' LEFT JOIN `city_uplink` ON `city_uplink`.id = `voip_service`.`city_uplink_id`'
				.' LEFT JOIN `zona_mobile_uplink` ON `zona_mobile_uplink`.id = `voip_service`.zona_mobile_uplink_id'
				.' LEFT JOIN `zona_mobile_uplink` `zona_mobile_uplink_reserve` ON `zona_mobile_uplink_reserve`.`id` = `voip_service`.`zona_mobile_uplink_reserve_id`'
				.' LEFT JOIN `zona_stationary_uplink` ON `zona_stationary_uplink`.id = `voip_service`.`zona_stationary_uplink_id`'
				.' LEFT JOIN `zona_stationary_uplink` `zona_stationary_uplink_reserve` ON `zona_stationary_uplink_reserve`.`id` = `voip_service`.`zona_stationary_uplink_reserve_id`'
				.' LEFT JOIN `long_distance_uplink` ON `long_distance_uplink`.id = `voip_service`.`long_distance_uplink_id`'
				.' LEFT JOIN `long_distance_uplink` `long_distance_uplink_reserve` ON `long_distance_uplink_reserve`.`id` = `voip_service`.`long_distance_uplink_reserve_id`'
				.' LEFT JOIN `international_uplink` ON `international_uplink`.id = `voip_service`.`international_uplink_id`'
				.' LEFT JOIN `international_uplink` `international_uplink_reserve` ON `international_uplink_reserve`.`id` = `voip_service`.`international_uplink_reserve_id`'
			    .' WHERE `service`.`id`=%d',
			$_GET['id']
		    );

			$querry_contract=sprintf
			(
				'SELECT'
					.' *'
				.' FROM'
					.' crm.contract'
				.' WHERE'
					.' account_id=('
									.' SELECT'
										.' account_id'
									.' FROM'
										.' crm.service'
									.' WHERE'
										.' id=%d)',
				$_GET['id']
			);
			//echo $querry_contract;
		}
		else
		{
		    $query = sprintf('SELECT * FROM `%s` WHERE `id`=%d',$_GET['action'],mysql_escape_string($_GET['id']));
		}

		$result= mysql_query($query);//||die(mysql_error());

		if ( $object = mysql_fetch_assoc($result) )
		{
		    $smarty->assign('object',$object);
		    

		    $result_contract = mysql_query($querry_contract);
			while( $row = mysql_fetch_assoc($result_contract) )
			{
				$contract_number[] = $row;
			}
			$smarty->assign('contract_numbers',$contract_number);

			$smarty->display(sprintf('admin/edit/%s.html',$_GET['action']));
		}
		else
		{
		    die(sprintf('Объект #%d класса \'%s\' не найден',$_GET['id'],$_GET['action']));
		}

	    }
	    break;

/*
	default:
	    print 'go to customer <a href="?action=customer.new">create</a>';
	    break;
*/
    }
}
?>
